I want to allow only numeric values to be entered into the text and if user enters alphabetic character it should warn the user. Any suggestion for optimized and short javas
This code uses the event
object's .keyCode
property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.
HTML:
<form>
<input type="text" id="txt" />
</form>
JS:
(function(a) {
a.onkeypress = function(e) {
if (e.keyCode >= 49 && e.keyCode <= 57) {}
else {
if (e.keyCode >= 97 && e.keyCode <= 122) {
alert('Error');
// return false;
} else return false;
}
};
})($('txt'));
function $(id) {
return document.getElementById(id);
}
For a result: http://jsfiddle.net/uUc22/
Mind you that the .keyCode
result for .onkeypress
, .onkeydown
, and .onkeyup
differ from each other.
Please note that, you should allow "system" key as well
$(element).keydown(function (e) {
var code = (e.keyCode ? e.keyCode : e.which), value;
if (isSysKey(code) || code === 8 || code === 46) {
return true;
}
if (e.shiftKey || e.altKey || e.ctrlKey) {
return ;
}
if (code >= 48 && code <= 57) {
return true;
}
if (code >= 96 && code <= 105) {
return true;
}
return false;
});
function isSysKey(code) {
if (code === 40 || code === 38 ||
code === 13 || code === 39 || code === 27 ||
code === 35 ||
code === 36 || code === 37 || code === 38 ||
code === 16 || code === 17 || code === 18 ||
code === 20 || code === 37 || code === 9 ||
(code >= 112 && code <= 123)) {
return true;
}
return false;
}
Here is a solution which blocks all non numeric input from being entered into the text-field.
html
<input type="text" id="numbersOnly" />
javascript
var input = document.getElementById('numbersOnly');
input.onkeydown = function(e) {
var k = e.which;
/* numeric inputs can come from the keypad or the numeric row at the top */
if ( (k < 48 || k > 57) && (k < 96 || k > 105)) {
e.preventDefault();
return false;
}
};