On my HTML page, I have an input text field that should only accept number keys and left/right arrow on the keyboard. I attempted to implement this using JavaScript, but encountered a problem.
<input onkeypress="return allowNumberOnly(event)" />
function allowNumberOnly(event) {
event = event || window.event;
var charCode = (event.which) ? event.which : event.keyCode;
//keyCode 48-57 represent the number 0-9
//keyCode 37,39 represent the Left and Right arrow
//keyCode 46 represent the Delete key
//keyCode 8 represent the Backspace key
return charCode == 37 || charCode == 39 || charCode == 46 || charCode == 8
|| (charCode >= 48 && charCode <= 57);
}
Upon testing, I discovered an issue where both the keyCode for the left arrow and the % special character are 37. This causes a conflict as I cannot prevent the entry of the % character while allowing the left arrow. I am puzzled by this unexpected behavior as I always believed each key on the keyboard would have a unique keyCode. I considered using onkeyup instead of onkeypress, but that would permit users to enter invalid characters first before removing them from the input text, which is not ideal. Any suggestions on how to address this issue?
Further debugging in FireFox revealed the following discrepancy:
1. Pressing % results in event.which == 37 and event.keyCode == 0
2. Pressing the Left Arrow results in event.which == 0 and event.keyCode == 37
By leveraging this difference, it seems like the problem has been resolved. I will continue to test in IE and Chrome to ensure consistent behavior.