Allow Numeric Only (0-9) In HTML Text Input Using JQuery




Here we consider how to Allow Numeric Only (0-9) In HTML Text Input Using JQuery. Suppose you have a textbox with ID txtNumeric. You want only numeric 0-9 entires on this textbox. If you are using HTML5, this validation can be achieved by following code.

Allow Numeric Only (0-9) In HTML Text Input Using JQuery, Allow Numeric Only (0-9) On textbox, Allow Numeric Only (0-9) On textbox Using Jquery, Allow Numeric Only (0-9) On textbox Validation, Allow Numeric Only, Allow Digits Only, Prevent Alpha Values, Asp.Net

This can be easily achieved by using Jquery. Inside keydown event of textbox, we have to write following code.

$(function () {
   $("#txtNumeric").keydown(function (e) {
       if ((e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
         (e.keyCode >= 35 && e.keyCode <= 40) ||
         $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1) {
         return;
      }
      if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) &&
         (e.keyCode < 96 || e.keyCode > 105)) {
          e.preventDefault();
      }
   });
});






In the above validation, following line ensure that it is a Number and Stop the keypress

if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57))
            && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
}



Following line Allow Ctrl+A and Command+A

(e.keyCode == 65 && ( e.ctrlKey === true || e.metaKey === true ) )


Following line Allow home, end, left, right, down and up keys

(e.keyCode >= 35 && e.keyCode <= 40)


Following line Allow backspace, delete, tab, escape, enter keys

$.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1


By providing the above validation, we can allow only numeric keys only.