Warm tip: This article is reproduced from stackoverflow.com, please click
html javascript

How to allow numbers, backspace, delete, left and right arrow keys in the html text?

发布于 2020-03-27 10:18:27

I am using following javascript code which I think should only allow numbers, backspace, delet, left arrow and right arrow keys in textbox, but it is also allowing alphabets. I don't know why?

function validateQty(event) {
    var key = window.event ? event.keyCode : event.which;

if (event.keyCode == 8 || event.keyCode == 46
 || event.keyCode == 37 || event.keyCode == 39) {
    return true;
}
else if ( key < 48 || key > 57 ) {
    return false;
}
else return true;
};

Calling this function as

<input type="text" onkeypress='validateQty(event)'>
Questioner
user1556433
Viewed
79
Ranjit Singh 2013-12-19 21:19

No doubt your code is correct but you missed "return" keyword in textbox.

<input type="text" onkeypress='return validateQty(event);'>

You can see the code here