Reputation: 5121
I found this solution which only accepts number in input.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
<input type="text" name="someid" onkeypress="return isNumberKey(event)" />
I tried to apply this in Vue way:
new Vue({
el: '#app',
methods: {
isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="app">
<input type="text" name="someid" @keypress="return isNumberKey($event)" />
</div>
And I get this error: avoid using JavaScript keyword as property name: "return" in expression @keypress="return isNumberKey($event)"
So, how do I make this work?
JSFiddle: http://jsfiddle.net/xr69Lhaw/1/
Upvotes: 0
Views: 642
Reputation: 5053
Vue element bindings will evaluate expressions, but an expression using the return keyword makes it impossible for Vue to execute, correctly.
Vue bindings are happy taking method references. So what you'd technically want is:
<input type="text" name="someid" @keypress="isNumberKey" />
Notice that we also removed the expression actually invoking isNumberKey($event)
. Simply, providing a reference to the method, Vue will call isNumberKey
and pass it an Event
object as the first argument.
Now, I'm not sure if simply returning false will cancel the keypress (if it does, please leave me a comment). But I'm sure that using preventDefault()
will do the trick, so you could technically rewrite your function as follows:
isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
evt.preventDefault();
}
Upvotes: 3