How to allow only numeric (0-9) in HTML inputbox using jQuery

Following example doesn’t allow any alphabetical character to enter in text box, any alpha key pressed will be halted whereas numeric value are only accepted in the text box.

Example

<!DOCTYPE html>
<html>
    <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
    </script>
    </head>
<body>
    <div>
      <form action="" method="get" name="form1">
        <label for="productPrice">Price 1</label>
        <input type="text" id="productPrice">
        <br />
        <label for="productPrice2">Price 2</label>
        <input type="text" id="productPrice2">
        <br />
        <br />
        <input type="submit">
      </form>
    </div>
    <script>
    $(document).ready(function() {
		// different ID's can be added with comma seperated ID's
          $("#productPrice,#productPrice2").keydown(function (e) {
            // Allow: backspace, delete, tab, escape, enter and .
            if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
                 // Allow: Ctrl+A
                (e.keyCode == 65 && e.ctrlKey === true) || 
                 // Allow: home, end, left, right, down, up
                (e.keyCode >= 35 && e.keyCode <= 40)) {
                     // let it happen, don't do anything
                     return;
            }
            // 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();
            }
        });
    });
    </script>
</body>
</html>
Share

You may also like...