The purpose of this JAVSCRIPT function is to prevent users from entering any alpha characters. If user enters those characters, the cursor does not move at all and stays at the same place. However if user enters a digit, cursor moves to the next position.
For example, in this text field, I only allow users to enter digits only. This method is working fine in all browsers except IE 8 and earlier. I tested it on Firefox, Chrome, and Safari and even in Safari emulator with no issues. If anybody guide me or even suggest me to modify my method so that it also works fine in IE that would be great help!!! Thank you
function AllowOnlyDigit(e) {
var ev = e || window.event;
var key = ev.keyCode || ev.which || ev.charCode;
if (key > 31 && (key < 48 || key > 57)) {
return false;
}
return true;
}
and this is how I am invoking this method :
<input type="text" onkeypress="return AllowOnlyDigit(event)" />
I would not use inline javascript but add the event listener from a script. I would then use a function to allow cross-browser event listeners to be added (in this example
addEvent
). I would probably do yourAllowOnlyDigit
differently too, but leaving it as is then you could try this. I don't have IE8 (or any windows products) to test with but it should work.HTML
Javascript
On jsfiddle
You can use this jquery function to enable only digites, points, comma:
You need to swap
onkeypress
foronkeydown
so you can cancel the event properly.