I have a text box and only want to accept numbers and a period "." when using VueJS. Can anyone help with code? I'm new to Vue.
You can use the <input> tag with attribute type='number'. This input field allows only numerical values. You can also specify the minimum value and maximum value that should be accepted by this field.
By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.
The v-model directive in Vue creates a two-way binding on the input element. All you need to do is simply declare a v-model directive for the input element and reference it to get the value. Every time the input value changes, “myInput” model will keep track of the changes.
You can write a Vue method and that method can be called on the keypress event. Check out this fiddle.
Update:
adding source code:
<div id="demo">
<input v-model="message" @keypress="isNumber($event)">
</div>
var data = {
message: 1234.34
}
var demo = new Vue({
el: '#demo',
data: data,
methods: {
isNumber: function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
evt.preventDefault();;
} else {
return true;
}
}
}
});
You should change your input to type="number"
to more accurately reflect your behaviour. You can then use the built-in Vue.js directive v-model.number
.
Usage:
<input type="number" v-model.number="data.myNumberData"/>
This was my solution. Most of the answers here have been deprecated. Additionally, input values always return a string, even if you key a number. So because of that, some of the solutions here did not work for me.
In my case I didn't want a decimal point, but I added that into the array for the purpose of this thread.
<b-form-input v-model.number="quantity" @keypress="isNumber($event)" type="number"></b-form-input>
isNumber (evt: KeyboardEvent): void {
const keysAllowed: string[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'];
const keyPressed: string = evt.key;
if (!keysAllowed.includes(keyPressed)) {
evt.preventDefault()
}
}
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