Only allow users to key in value like currency in a text box by using Vue.js
Working example: https://jsfiddle.net/0s14cbqx/
In template:
<input placeholder="Name a price" v-model="price" @keypress="onlyForCurrency">
In js:
data(){
return{
price:null
}
},
methods: {
onlyForCurrency ($event) {
// console.log($event.keyCode); //keyCodes value
let keyCode = ($event.keyCode ? $event.keyCode : $event.which);
// only allow number and one dot
if ((keyCode < 48 || keyCode > 57) && (keyCode !== 46 || this.price.indexOf('.') != -1)) { // 46 is dot
$event.preventDefault();
}
// restrict to 2 decimal places
if(this.price!=null && this.price.indexOf(".")>-1 && (this.price.split('.')[1].length > 1)){
$event.preventDefault();
}
}
}
In this way, users only can key in numbers and one dot and can't key in anything after 2 decimal places.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With