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?