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)'>
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
yes, it works. But problem occurs when I copy paste any alphabet.
@nkp - if you paste a value without using the keyboard then obviously a
keypress
handler is not going to catch it. If you paste with the keyboard you need to test for that withkeydown
, because I don't think paste triggers akeypress
event. (Might be simpler to just remove unwanted charactersonblur
...)@Learning - yes, that I know. Just wanted to go one step further
@Learning - If I call same function on onkeydown event, even numeric values are not copied to text.
@nkp - The comment you seem to be replying to was mine. I didn't say to call the same function on keydown, I just noted that you might need to use keydown in some way if you want to catch a keyboard-based paste. Again, removing unwanted characters on blur might be easier, because users can put text in a field without using the keyboard or the clipboard (using drag'n'drop).