When quickly typing, the input formatting using a computed property in Vue.js is not getting applied

Is there a way to format data in the following manner: m:ss, while restricting the input textbox to display only 3 characters or fewer? (m = minute, s = seconds)

The code snippet below successfully formats the data in m:ss format. However, when entering multiple characters at once, the textbox may show more than 3 characters or become unresponsive.

For example, typing '11111' might result in '1:1111', but the desired output is '1:11'.

In some cases like entering '1234', it may freeze at '1:2'. Subsequent inputs then exceed 3 characters.

new Vue({
  el:"#app",
  data () { return { value: "" } },
  computed: {
    fValue: {
      // getter
      get () {
        if (this.value.length > 3) { return this.value.substr(0, 3); }
        return this.value;
      },
      // setter
      set (newValue) {
        this.formatTime(newValue);
      }
    }
  },
  methods: {
    formatTime (str) {
      let totalLength = str.length;
      if (totalLength > 3) { totalLength = 3; }
      let a = str.replace(/[^0-9]/g, "").substr(0, 1);
      let b = str.replace(/[^0-9]/g, "").substr(1, 1);
      if (b > 5) { b = 5; }
      const c = str.replace(/[^0-9]/g, "").substr(2, 1);
      if (totalLength >= 2) { a = `${a.substring(0, 1)}:${b}${c}`; }
      const result = a;
      this.value = result;
      return result;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input
    v-model="fValue"
    id="format-value"
    class="input"
    type="text"
  />
</div>

------ EDIT Question 2 -----

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
   <div
      v-for="(index) in valueInputs" <-- index
      :key="index"
    >
      <input
        v-model="value"     // <-- I want to track what index I'm in
        @input="formatTime" // <-- so I can set it in an array later
        maxLength="4"       // I tried formatTime[index] or value[index]
        id="format-value"
        class="input"
        type="text"
      />
  </div>
</div>

data () {
  return {
  valueInputs: [],    // a list of inputs
  allFormatValues: [] // want to store all the formatted values here by the index
 }
}

To create an array that saves all formatted values:

this.allFormatValues[index] = this.value;

Unsure how to link the index with the formatted string value. Any suggestions?

Answer №1

To implement the functionality, utilize value as the v-model and invoke formatTime on input. A demonstration is provided below with some refactoring and enhancements:

new Vue({
  el:"#app",
  data () { return { value: "" } },
  methods: {
    formatTime () {
      const numericValue = this.value.replace(/[^0-9]/g, "");
      let [a = '', b = '', c = ''] = numericValue.substr(0, 3).split('');
      b = b > 5 ? 5 : b;
      this.value = numericValue.length >= 2 ? `${a}:${b}${c}` : a;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input
    v-model="value"
    @input="formatTime"
    maxLength="4"
    id="format-value"
    class="input"
    type="text"
  />
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Using private API keys in Nuxt to trigger a request upon clicking a button: a step-by-step guide

I've stored my API credentials securely in the privateRuntimeConfig option within the nuxt.config.js file to prevent client-side access. However, I'm facing a dilemma when it comes to sending requests to the API after a user clicks a button. In ...

React.map does not retrieve the specific value

I am facing an issue with my list of items. I have implemented it using mui list, and I have also added a button for editing the list. However, when I click on an item, I am getting the value of the last item instead of the one I clicked on. Below is my f ...

What is the best way to manage numerous asynchronous post requests in AngularJS?

$scope.savekbentry = function (value) { console.log('save clicked'); console.log(value); console.log($scope.kbentry.kbname); $scope.kbentry.mode = value; var kbname = $scope.kbentry.kbname; var kbd ...

Vue's computed property utilizing typed variables

I am trying to create a computed array of type Todo[], but I keep encountering this specific error: No overload matches this call. Overload 1 of 2, '(getter: ComputedGetter<Todo[]>, debugOptions?: DebuggerOptions | undefined): ComputedRef<T ...

Exploring the Power of Asynchronous Operations with Await and Async in

I have a basic understanding of how to use await/async in Angular 2 with the following example: async getValueWithAsync() { const value = <number>await this.resolveAfter2Seconds(20); console.log(`async result: ${value}`); } In my Angular ...

Should V-for be used within V-if in Vue.js for optimal coding practices?

During a recent project, we utilized the following code: <template> <div id="app"> <button @click="fetch">Fetch numbers</button> <div v-if="!getNumbers.length">Waiting for numbers...</div> <div v-if=" ...

Error: JSON array contains unterminated string literal

Hey there, var favorites = 'Array ( [0] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [1] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] [2] => [" 6 "," 1 "," 2 "," 5 "," 3 "," 4 "] ) '; I've been encountering a syntax error - an untermi ...

The Navbar is throwing a TypeError because it is unable to retrieve the property 'classList' of null

I am currently experimenting with building a navbar in HTML that has the capability to dynamically switch pages without changing links using href. The method I'm employing to achieve this involves adding a classList of is-active to the div elements wi ...

The optimal method for computing the Fibonacci sequence using JavaScript

Improving my skills in optimizing algorithms and understanding big-o notation is a priority for me. I devised the following function to compute the n-th Fibonacci number. It works well for higher inputs, but I wonder how I can enhance it. What are the dow ...

Retrieving the checkbox's status from the database

I have implemented a basic checkbox that updates its state in the database when clicked or unclicked. Is there a way to retain this state and have it displayed as checked if the page is refreshed? Essentially, I want the checkbox to remember its last state ...

Is there a way to incorporate locales in calculations involving percentages?

Given the number 4030.146852312 I want to retrieve the four decimal places from this number, resulting in: 4030.1468 Furthermore, I need to format this number according to the specified locale. For example: 4.030,1468 What is the best way to achieve thi ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

Location of Ajax callback function

I encountered an issue with a callback function that was placed within $(document).ready. The callback function wasn't functioning as expected. Surprisingly, when I moved it outside of $(document).ready, the code started working flawlessly. I am puzzl ...

Update the total in the input field by aggregating data from multiple input fields in a Vue2 component

When receiving a response from an API, I am generating a variable number of input fields for product quantity. Each input field takes a number as input and I need to update the total price for each item and the subtotal for all items when the user changes ...

Exploring network connectivity using Node.js

As someone who is just starting out with the node super framework, I'm curious to find out if there's a library or sub framework in Node.js that allows users to ping a server from the frontend of a web app. Ideally, this tool would provide variou ...

MinifyJS - optimize all .js files within a directory

Seeking assistance to finalize my build process: I am currently transpiling es6 > es5 using babel. Once that is complete, I aim to minify all my .js files recursively with uglifyJS solely using NPM scripts (no grunt or gulp). My Requirements; Convert ...

Sorting items using jQuery filter

I am working with two sortable div containers that are connected using connectWith. Both containers contain draggable items that can be moved as desired. These items have specific classes such as group1 and group2. Let's refer to the containers as con ...

Exploring the power of Angular by implementing nested ng-repeat functionalities:

I am currently working on an ng-repeat feature to add items from the array (album array). Everything seems to be functioning correctly. However, I also have a colors array that should assign different background-colors to the card elements of the album arr ...