987

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery?

19
  • 79
    Keep in mind that you cannot rely on client-side validation - you also need to validate on the server in case the user has JavaScript turned off, or isn't using a JavaScript compatible browser. Commented Jun 15, 2009 at 9:50
  • 51
    have you considered html5? <input type="number" />. with min and max attributes you can restrict input too Commented Apr 11, 2012 at 4:33
  • 6
    I think you should check for input values on the keyup event and not check for keycodes, because it's much more reliable across differences in keyboards and what not. Commented Jun 20, 2012 at 8:08
  • 14
    I fully agree with Richard: do not use keycodes. The accepted answer does not work on French keyboards, for example, since you need to press "Shift" in order to type numbers on those keyboards. Keycodes are just too risky, IMHO. Commented Dec 12, 2012 at 14:15
  • 3
    @ZX12R Doesn't work in any current versions of IE. It's all well and good to use the latest code on your own stuff to keep fresh, but this isn't really an option for almost any professional project. caniuse.com/#feat=input-number Commented Mar 20, 2013 at 13:53

70 Answers 70

1366

Note: This is an updated answer. Comments below refer to an old version which messed around with keycodes.

jQuery

Try it yourself on JSFiddle.

There is no native jQuery implementation for this, but you can filter the input values of a text <input> with the following inputFilter plugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and all browsers since IE 9):

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(callback, errMsg) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
      if (callback(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          $(this).removeClass("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        $(this).addClass("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  };
}(jQuery));

You can now use the inputFilter plugin to install an input filter:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  },"Only digits allowed");
});

Apply your preferred style to input-error class. Here's a suggestion:

.input-error{
  outline: 1px solid red;
}

See the JSFiddle demo for more input filter examples. Also note that you still must do server side validation!

Pure JavaScript (without jQuery)

jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See this answer.

HTML 5

HTML 5 has a native solution with <input type="number"> (see the specification), but note that browser support varies:

  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsers don't support the step, min and max attributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters e and E into the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter any text into the field.

Try it yourself on w3schools.com.

Sign up to request clarification or add additional context in comments.

25 Comments

Thanks! event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 if you want decimals
Add keyCodes 37 and 39 to allow left and right arrow navigation in the txt box for example: if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 37 || event.keyCode == 39)
ooo, just picked up an issue for this from our testers. You have to prevent the user from holding down shift and hitting the numeric keys, otherwise the input will allow !@#$%^&*()
Confirmed the shift+ bug. Also, ALT+ number pad allows pretty much anything (i.e. Alt+321 = A, Alt+322 = B, etc...). Another case for server side validation.
I really disagree with this answer: it is really too risky playing with keycodes, because you cannot be sure what the keyboard layout is. For example, on French keyboards, users have to press shift in order to type numbers. So this code will not work at all. So please go for validation instead of this keycode hack.
|
203

Here is the function I use:

// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, enter, arrows, numbers and keypad numbers ONLY
            // home, end, period, and numpad decimal
            return (
                key == 8 || 
                key == 9 ||
                key == 13 ||
                key == 46 ||
                key == 110 ||
                key == 190 ||
                (key >= 35 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        });
    });
};

You can then attach it to your control by doing:

$("#yourTextBoxName").ForceNumericOnly();

10 Comments

i found this useful, but i found a anoying "bug". when i use this on my iMac, it allows some letter, like a and e. it seems like the keypad numbers on the pc is letters on the iMac and the Mac keyboard is the same as the regular numbers. anyone know how to make it work on both mac and pc?
Keys "Home", "End" is not working too. This is a better solution which Peter suggested: west-wind.com/weblog/posts/2011/Apr/22/…
Why is there a return this.each(function() ?
@powtac - so you can call .ForceNumericOnly() on multiple objects. For example... $("input[type='text']").ForceNumericOnly()
@powtac the each from return this.each(function() is to allow multiple objects as HaggleLad said, and the return part is to return the jQuery object back to the caller, to allow chaining such as $("input[type='text'").ForceNumericOnly().show()
|
182

Inline:

<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">

Unobtrusive style (with jQuery):

$('input[name="number"]').keyup(function(e)
                                {
  if (/\D/g.test(this.value))
  {
    // Filter non-digits from input value.
    this.value = this.value.replace(/\D/g, '');
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="number">

14 Comments

This moves the caret to the end even if the user is pressing left arrow key.
@phrogz, try this: onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')".
At least on Chrome 24, this causes the non-number to appear and then it is immediately deleted, which looks pretty cheesy (compared to preventing the non-number from being entered in the first place).
@mhenry1384 That is expected behavior. I find it to be nice feedback but if you don't like that, then a key code approach would be what you're looking for.
You could modify to /[^0-9]|^0+(?!$)/g to prevent leading series of zero.
|
110

You can use on input event like this:

$(document).on("input", ".numeric", function() {
    this.value = this.value.replace(/\D/g,'');
});

But, what's this code privilege?

  • It works on mobile browsers(keydown and keyCode have problem).
  • It works on AJAX generated content too, because We're using "on".
  • Better performance than keydown, for example on paste event.

5 Comments

I feel like this is a much more robust (and simpler) solution than the accepted answer.
Even simpler if using replace(/\D/g, '')
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
I would suggest using this.value = Number(this.value.replace(/\D/g, ''));
Good answer, allows to easily toggle whether an input is numeric or not by toggling class
107

You could just use a simple JavaScript regular expression to test for purely numeric characters:

/^[0-9]+$/.test(input);

This returns true if the input is numeric or false if not.

or for event keycode, simple use below :

     // Allow: backspace, delete, tab, escape, enter, ctrl+A 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
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }

    var charValue = String.fromCharCode(e.keyCode)
        , valid = /^[0-9]+$/.test(charValue);

    if (!valid) {
        e.preventDefault();
    }

3 Comments

See my answer for an implementation of this approach.
wouldn't it take less processor time to check for a numerical keypress rather then checking a regular expression?
This would not prevent pasting letters with CTRL+V right?
73
+50

Short and sweet:

$('#number_only').bind('keyup paste', function(){
      this.value = this.value.replace(/[^0-9]/g, '');
});

3 Comments

I'd replace keyup by input, otherwise you can maintain a letter pressed then click to take the focus out of the textbox and it leave the text as is. input assure that this can't happen
Thanks for the regex - but this is a tad better event handler: $('#number_only').on('input propertychange', function(){ this.value = this.value.replace(/[^0-9]/g, ''); });
FYI - The question didn't ask for it, but this doesn't allow for decimals (eg. 12.75). Binding "input" rather than "keyup" makes for a smoother UX instead of seeing their character for a split second, then having it removed.
45

Use JavaScript function isNaN,

if (isNaN($('#inputid').val()))

if (isNaN(document.getElementById('inputid').val()))

if (isNaN(document.getElementById('inputid').value))

Update: And here a nice article talking about it but using jQuery: Restricting Input in HTML Textboxes to Numeric Values

4 Comments

Well... "Not using JQuery" except for the part of your example that is using JQuery...
document.getElementById('inputid').val() dude.. that's still jquery. .val() is a jquery thing. use .value
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
33
$(document).ready(function() {
    $("#txtboxToFilter").keydown(function(event) {
        // Allow only backspace and delete
        if ( event.keyCode == 46 || event.keyCode == 8 ) {
            // let it happen, don't do anything
        }
        else {
            // Ensure that it is a number and stop the keypress
            if (event.keyCode < 48 || event.keyCode > 57 ) {
                event.preventDefault(); 
            }   
        }
    });
});

Source: http://snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values

4 Comments

Wow, empty "if" blocks and magic numbers both! I just threw up in my mouth a little. :D But seriously, why go to all this trouble when you could just match the input against the regex /^[.\d]+$/ ? And what does the '8' represent?
@Alan: Haha, I have no idea - I copied directly from the source. I'd write "if(event.keyCode != 46 && event.keyCode != 8)" instead, or use regex as you said. I suppose the 8 represents the delete key.
Try pressing Shift + 8 for instance - your validation will let * get in
This is nice.Would be much better,If it handles the Shift key+Numbers (Special chars like !@#$%^..)
31

I use this in our internal common js file. I just add the class to any input that needs this behavior.

$(".numericOnly").keypress(function (e) {
    if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

1 Comment

Nice, elegant and useful code! Thanks. But you must add keyup and keydown events.
26

Why so complicated? You don't even need jQuery because there is a HTML5 pattern attribute:

<input type="text" pattern="[0-9]*">

The cool thing is that it brings up a numeric keyboard on mobile devices, which is way better than using jQuery.

3 Comments

This should have a lot more votes. If anything, you could also add a fall back regex for non-html5 browsers - but validation of data should be handled server-side anyways.
it looks like it's well supported by most browsers by now, so modernizr support isn't so important: caniuse.com/#search=pattern Safari works very well even though it's listed as partially supported on this site. Try it!
@guest Thank you so much for this. Quickest and easiest answer! Top answer in my opinion.
26

Simpler one for me is:

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});

1 Comment

Just need to be sure you use this.value.replace(/[^0-9\.]/g,''); to include OP's requirements of 0-9
22

You can do the same by using this very simple solution:

$("input.numbers").keypress(function(event) {
  return /\d/.test(String.fromCharCode(event.keyCode));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="numbers" name="field_name" />

I referred to this link for the solution.

3 Comments

Maybe this is better /\d|\./ to allow . decimal numbers
This works perfect in crome. But not in Mozilla FireFox
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
14

You can try the HTML5 number input:

<input type="number" value="0" min="0"> 

For non-compliant browsers there are Modernizr and Webforms2 fallbacks.

1 Comment

this still allows comma's
14

The pattern attribute in HTML5 specifies a regular expression that the element's value is checked against.

  <input  type="text" pattern="[0-9]{1,3}" value="" />

Note: The pattern attribute works with the following input types: text, search, url, tel, email, and password.

  • [0-9] can be replaced with any regular expression condition.

  • {1,3} it represents minimum of 1 and maximum of 3 digit can be entered.

2 Comments

hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
@transformer try this <input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="0.01">
12
function suppressNonNumericInput(event){
        if( !(event.keyCode == 8                                // backspace
            || event.keyCode == 46                              // delete
            || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
            || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
            || (event.keyCode >= 96 && event.keyCode <= 105))   // number on keypad
            ) {
                event.preventDefault();     // Prevent character input
        }
    }

2 Comments

hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
Great solution. Add keyCode 9 as well to allow TAB
11

Something fairly simple using jQuery.validate

$(document).ready(function() {
    $("#formID").validate({
        rules: {
            field_name: {
                numericOnly:true
            }
        }
    });
});

$.validator.addMethod('numericOnly', function (value) {
       return /^[0-9]+$/.test(value);
}, 'Please only enter numeric values (0-9)');

Comments

11

Here is two different approaches:

  1. Allow numeric values with decimal point
  2. Allow numeric values without decimal point

APPROACH 1:

$("#approach1").on("keypress keyup blur",function (e) {
   $(this).val($(this).val().replace(/[^0-9\.]/g,''));
      if ((e.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
          event.preventDefault();
      }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric with decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach1">

APPROACH 2:

$("#approach2").on("keypress keyup blur",function (event) {    
   $(this).val($(this).val().replace(/[^\d].+/, ""));
    if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2>Numeric without decimal point</h2><br/>
<span>Enter Amount</span>
<input type="text" name="amount" id="approach2">

1 Comment

Can you explain to me what : ] you used? Because I did not understand it and thank you for the code
11

If have a smooth OneLiner:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >

1 Comment

Great solution but is onkeypress not depreciated? Replacing this with onkeydown actually causes a problem, it does not allow a backspace?
10

Try it within html code it self like onkeypress and onpaste:

<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false">

Comments

8

You can use this JavaScript function:

function maskInput(e) {
    //check if we have "e" or "window.event" and use them as "event"
        //Firefox doesn't have window.event 
    var event = e || window.event 

    var key_code = event.keyCode;
    var oElement = e ? e.target : window.event.srcElement;
    if (!event.shiftKey && !event.ctrlKey && !event.altKey) {
        if ((key_code > 47 && key_code < 58) ||
            (key_code > 95 && key_code < 106)) {

            if (key_code > 95)
                 key_code -= (95-47);
            oElement.value = oElement.value;
        } else if(key_code == 8) {
            oElement.value = oElement.value;
        } else if(key_code != 9) {
            event.returnValue = false;
        }
    }
}

And you can bind it to your textbox like this:

$(document).ready(function() {
    $('#myTextbox').keydown(maskInput);
});

I use the above in production, and it works perfectly, and it is cross-browser. Furthermore, it does not depend on jQuery, so you can bind it to your textbox with inline JavaScript:

<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>

1 Comment

This fails when someone pastes non numeric text in the input . Any ide a how we could overcome this ? Can't wrap my mind over this .
8

A very good and simple solution that doesn't prevent the user from selecting text or copy pasting as other solutions do (jQuery style):

$("input.inputPhone").keyup(function() {
    var jThis=$(this);
    var notNumber=new RegExp("[^0-9]","g");
    var val=jThis.val();
    
    //Math before replacing to prevent losing keyboard selection 
    if(val.match(notNumber))
    { jThis.val(val.replace(notNumber,"")); }
}).keyup(); //Trigger on page load to sanitize values set by server

1 Comment

Hey i am using this but what i am really looking is to allow him dot like 1.2 or 3.455 like that
7

I think this will:

  $('input.valid-number').bind('keypress', function(e) { 
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
  })

1 Comment

you're forgetting about keypad input. This would include that: if(event.which!=8 && event.which!=0 && (event.which<48 || event.which>57) && (event.which<96 || event.which>105)) return;
7

Here is a quick solution to Allow only numbers (numeric) in a field with jQuery:

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});

Comments

6

You would want to allow tab:

$("#txtboxToFilter").keydown(function(event) {
    // Allow only backspace and delete
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
        // let it happen, don't do anything
    }
    else {
        // Ensure that it is a number and stop the keypress
        if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
            event.preventDefault(); 
        }   
    }
});

Comments

6

Here is an answer that uses jQuery UI Widget factory. You can customize what characters are allowed easily.

$('input').numberOnly({
    valid: "0123456789+-.$,"
});

That would allow numbers, number signs and dollar amounts.

$.widget('themex.numberOnly', {
    options: {
        valid : "0123456789",
        allow : [46,8,9,27,13,35,39],
        ctrl : [65],
        alt : [],
        extra : []
    },
    _create: function() {
        var self = this;

        self.element.keypress(function(event){
            if(self._codeInArray(event,self.options.allow) || self._codeInArray(event,self.options.extra))
            {
                return;
            }
            if(event.ctrlKey && self._codeInArray(event,self.options.ctrl))
            {
                return;
            }
            if(event.altKey && self._codeInArray(event,self.options.alt))
            {
                return;
            }
            if(!event.shiftKey && !event.altKey && !event.ctrlKey)
            {
                if(self.options.valid.indexOf(String.fromCharCode(event.keyCode)) != -1)
                {
                    return;
                }
            }
            event.preventDefault(); 
        });
    },

    _codeInArray : function(event,codes) {
        for(code in codes)
        {
            if(event.keyCode == codes[code])
            {
                return true;
            }
        }
        return false;
    }
});

1 Comment

does this ensure $ and then + - as first or first/second characters and then only 1 decimal point?
6

This seems unbreakable:

// Prevent NULL input and replace text.
$(document).on('change', 'input[type="number"]', function (event) {
    this.value = this.value.replace(/[^0-9\.]+/g, '');
    if (this.value < 1) this.value = 0;
});

// Block non-numeric chars.
$(document).on('keypress', 'input[type="number"]', function (event) {
    return (((event.which > 47) && (event.which < 58)) || (event.which == 13));
});

Comments

6

I wrote mine based off of @user261922's post, slightly modified so you can select all, tab and can handle multiple "number only" fields on the same page:

var prevKey = -1, prevControl = '';
$(document).ready(function () {
    $(".OnlyNumbers").keydown(function (event) {
        if (!(event.keyCode == 8                                // backspace
            || event.keyCode == 9                               // tab
            || event.keyCode == 17                              // ctrl
            || event.keyCode == 46                              // delete
            || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
            || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
            || (event.keyCode >= 96 && event.keyCode <= 105)    // number on keypad
            || (event.keyCode == 65 && prevKey == 17 && prevControl == event.currentTarget.id))          // ctrl + a, on same control
        ) {
            event.preventDefault();     // Prevent character input
        }
        else {
            prevKey = event.keyCode;
            prevControl = event.currentTarget.id;
        }
    });
});

Comments

6

I also would like to answer:

$('.justNum').keydown(function(event){
    var kc, num, rt = false;
    kc = event.keyCode;
    if(kc == 8 || ((kc > 47 && kc < 58) || (kc > 95 && kc < 106))) rt = true;
    return rt;
})
.bind('blur', function(){
    num = parseInt($(this).val());
    num = isNaN(num) ? '' : num;
    if(num && num < 0) num = num*-1;
    $(this).val(num);
});

That's it...just numbers. Almost it can work just with the 'blur', but...

Comments

6

This method only allows 0-9 both keyboard and numpad, backspaces, tab, left and right arrows (normal form operations):

$(".numbersonly-format").keydown(function (event) {
    // Prevent shift key since its not needed
    if (event.shiftKey == true) {
        event.preventDefault();
    }
    // Allow Only: keyboard 0-9, numpad 0-9, backspace, tab, left arrow, right arrow, delete
    if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) {
        // Allow normal operation
    } else {
        // Prevent the rest
        event.preventDefault();
    }
});

Comments

5

I wanted to help a little, and I made my version, the onlyNumbers function...

function onlyNumbers(e){
    var keynum;
    var keychar;

    if(window.event){  //IE
        keynum = e.keyCode;
    }
    if(e.which){ //Netscape/Firefox/Opera
        keynum = e.which;
    }
    if((keynum == 8 || keynum == 9 || keynum == 46 || (keynum >= 35 && keynum <= 40) ||
       (event.keyCode >= 96 && event.keyCode <= 105)))return true;

    if(keynum == 110 || keynum == 190){
        var checkdot=document.getElementById('price').value;
        var i=0;
        for(i=0;i<checkdot.length;i++){
            if(checkdot[i]=='.')return false;
        }
        if(checkdot.length==0)document.getElementById('price').value='0';
        return true;
    }
    keychar = String.fromCharCode(keynum);

    return !isNaN(keychar);
}

Just add in input tag "...input ... id="price" onkeydown="return onlyNumbers(event)"..." and you are done ;)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.