I'm currently working on creating a utility method in Vue.js to validate decimal numbers from any input field, but I am facing difficulty in persisting the value internally within Vue.js.
In the past, when using jQuery, I used this approach:
$('body').on('blur', '.decimal', function() {
var val = $(this).val();
if ($.isNumeric(val)) {
val = parseFloat(val).toFixed(2);
$(this).val(val);
} else {
$(this).val('');
}
});
Although in Vue, my implementation seems to be overwriting the value without storing it internally as intended.
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
methods: {
validateDecimal: function (e) {
var val = e.target.value;
if (isNumeric(val)) {
e.target.value = parseFloat(val).toFixed(2);
} else {
e.target.value = '';
}
}
}
HTML
<input class="ui-input" :value="some.value" placeholder="0.00" @blur="validateDecimal">
<input class="ui-input" :value="some.othervalue" placeholder="0.00" @blur="validateDecimal">
<input class="ui-input" :value="another.dynamic.input" placeholder="0.00" @blur="validateDecimal">