how to allow only numbers in textbox using jquery


I have a web application and i want a textbox in which user cannot type any thing expcet numeric(0-9) data.

How can we achieve this using jquery?

thanks


Asked by:- Vinnu
2
: 386 At:- 6/9/2017 4:49:22 PM
jquery javascript only numbers






2 Answers
profileImage Answered by:- vikas_jk

I have a simple and quick solution for it, use this jquery code

$(document).ready(function() {
    $("#txtboxToFilter").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, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === 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();
        }
    });
});

it should work, test it and let me know, thanks

1
At:- 6/9/2017 5:27:20 PM


profileImage Answered by:- manish

Here is another solution to allow only  numbers ins textbox using jquery

$(document).ready(function () {
  //called when key is down
  $("#number").bind("keydown", function (event) {
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
             // Allow: Ctrl+A
            (event.keyCode == 65 && event.ctrlKey === true) || 
 
        // Allow: home, end, left, right
            (event.keyCode >= 35 && event.keyCode <= 39)) {
              // let it happen, don't do anything
              return;
        } else {
            // Ensure that it is a number and stop the keypress
            if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
                event.preventDefault();
            }
        }
   });
});

this code will allow only numbers, and it will not allow cut-copy-paste in textbox

0
At:- 7/15/2017 8:38:21 AM Updated at:- 7/15/2017 8:38:48 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use