Monday, December 26, 2011

Javascript Input field to accept only numbers

Javascript Input field to accept only numbers:

The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.

$(".numeric").keypress(function(event) {
// Backspace, tab, enter, end, home, left, right
// We don't support the del key in Opera because del == . == 46.
var controlKeys = [8, 9, 13, 35, 36, 37, 39];
// IE doesn't support indexOf
var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
// Some browsers just don't raise events for control keys. Easy.
// e.g. Safari backspace.
if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
(49 <= event.which && event.which <= 57) || // Always 1 through 9
(48 == event.which && $(this).attr("value")) || // No 0 first digit
isControlKey) { // Opera assigns values for control keys.
return;
} else {
event.preventDefault();
}
});

reference : Link to input field numbers only

No comments: