I am trying to implement onkeypress
event in a Vue ponent. On keypress I want to restrict all key codes except numbers. I am trying the following.
Using the onkeypress event, things work fine!
<input type="number" onkeypress="return (event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode)));" />
When I convert the above to be used in Vue, it does not work!!! :(
<input type="number" @keypress="restrictChars($event)" />
<script>
export default {
name: 'quantity-selector',
methods: {
restrictChars: function($event) {
return ($event.charCode === 0 || /\d/.test(String.fromCharCode($event.charCode)));
}
}
What am I missing?? I don't understand what is going wrong? Any help is hugely appreciated!
I am trying to implement onkeypress
event in a Vue ponent. On keypress I want to restrict all key codes except numbers. I am trying the following.
Using the onkeypress event, things work fine!
<input type="number" onkeypress="return (event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode)));" />
When I convert the above to be used in Vue, it does not work!!! :(
<input type="number" @keypress="restrictChars($event)" />
<script>
export default {
name: 'quantity-selector',
methods: {
restrictChars: function($event) {
return ($event.charCode === 0 || /\d/.test(String.fromCharCode($event.charCode)));
}
}
What am I missing?? I don't understand what is going wrong? Any help is hugely appreciated!
v-model.number="yourmodel" @input="restrictChars"
– Boussadjra Brahim
Commented
Nov 16, 2018 at 23:51
Figured out the problem. Though I was returning a boolean when reading the keyCodes, I wasn't preventing the default keypress action. The restrictChars
method should look something like this!
restrictChars: function($event) {
if ($event.charCode === 0 || /\d/.test(String.fromCharCode($event.charCode))) {
return true
} else {
$event.preventDefault();
}
}