This example will explain you how to validate input integers using JavaScript. Though they are many ways to validate input data, we will use here one of the efficient way to achieve this using JavaScript.
<!DOCTYPE html> <html> <body> <label for="txtExample1">Example 1:</label> <input type="text" id="txtExample1" onKeyPress="return onlyNumbers();" /> <label for="txtExample2">Example 2:</label> <input type="text" id="txtExample2" onKeyUp="isNumeric(this);" /> </body> </html>
function onlyNumbers(evt) { var e = event || evt; // for trans-browser compatibility var charCode = e.which || e.keyCode; if (charCode & #x3E; 31 & #x26; & #x26; (charCode & #x3C; 48 || charCode & #x3E; 57)) return false; return true; }
function isNumeric(x) { var s_len = x.value.length; var s_charcode = 0; for (var s_i = 0; s_i < s_len; s_i++) { s_charcode = x.value.charCodeAt(s_i); if (!((s_charcode >= 48 && s_charcode <= 57))) { alert("Only Numeric Values Allowed"); x.value = ''; x.focus(); return false; } } return true; }