[jquery] How to allow only numeric (0-9) in HTML inputbox using jQuery?

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?

This question is related to jquery html validation numeric

The answer is


Short and sweet - even if this will never find much attention after 30+ answers ;)

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

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

For general purpose, you can have JS validation as below:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input type="someid" name="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML Text Input allow only Numeric input

JSFiddle demo: http://jsfiddle.net/Gagan_Gami/nSjy7/333/


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 ;)


jQuery("#no_of").keypress(function(event){
    //Allow only backspace and delete
    if (event.keyCode != 46 && event.keyCode != 8) {
        if (!parseInt(String.fromCharCode(event.which))) {
            event.preventDefault();
        }
    }
});

jQuery("#no_of").keyup(function(e){
    var temp_s= jQuery("#no_of").val();
    var multiply_val= temp_s*10;
    jQuery("#ex-r").html(multiply_val);
});

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));
});

Here is a quick solution I created some time ago. you can read more about it in my article:

http://ajax911.com/numbers-numeric-field-jquery/

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

This is what I use to validate number inputs for integer or float values (unobtrusive style with jQuery):

_x000D_
_x000D_
$('input[name="number"]').keyup(function(e) {_x000D_
    var float = parseFloat($(this).attr('data-float'));_x000D_
_x000D_
    /* 2 regexp for validating integer and float inputs *****_x000D_
        > integer_regexp : allow numbers, but do not allow leading zeros_x000D_
        > float_regexp : allow numbers + only one dot sign (and only in the middle of the string), but do not allow leading zeros in the integer part_x000D_
    *************************************************************************/_x000D_
    var integer_regexp = (/[^0-9]|^0+(?!$)/g);_x000D_
    var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g);_x000D_
_x000D_
    var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;_x000D_
    if (regexp.test(this.value)) {_x000D_
        this.value = this.value.replace(regexp, '');_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" data-float="1" id="number" name="number" placeholder="integer">_x000D_
<input type="text" data-float="0.1" id="number" name="number" placeholder="float">
_x000D_
_x000D_
_x000D_


Many people here are using keycode property which is not easy to remember. If you do not have a locale issues then you can simply use key which is actually the input that user types.

See this Fiddle

_x000D_
_x000D_
$("#txt").on("keypress",function(e){_x000D_
  console.log("Entered Key is " + e.key);_x000D_
  switch (e.key)_x000D_
     {_x000D_
         case "1":_x000D_
         case "2":_x000D_
         case "3":_x000D_
         case "4":_x000D_
         case "5":_x000D_
         case "6":_x000D_
         case "7":_x000D_
         case "8":_x000D_
         case "9":_x000D_
         case "0":_x000D_
         case "Backspace":_x000D_
             return true;_x000D_
             break;_x000D_
_x000D_
         case ".":_x000D_
             if ($(this).val().indexOf(".") == -1) //Checking if it already contains decimal. You can Remove this condition if you do not want to include decimals in your input box._x000D_
             {_x000D_
                 return true;_x000D_
             }_x000D_
             else_x000D_
             {_x000D_
                 return false;_x000D_
             }_x000D_
             break;_x000D_
_x000D_
         default:_x000D_
             return false;_x000D_
     }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
Enter Value_x000D_
<input id="txt" type="text" />
_x000D_
_x000D_
_x000D_

issue then see the following simple code.

Please note that this example also contains validation for decimal entry.

As per this question it is not required so you can simply remove the case "." to remove entry of decimal.


I recommend to check event.metaKey as well. If that's set to true, the user might be doing something like cmd-A to select all the text in the field. You should allow that too.


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;
    }
});

I wrote mine based off of @user261922's post above, 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;
        }
    });
});

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();
    }

You can use the following code.

_x000D_
_x000D_
<input type="text" onkeypress="return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57">
_x000D_
_x000D_
_x000D_


There is an incredible compatibility issue with using keystrokes to detect the character pressed... see quirksmode to know more about that.

I would suggest using keyup to create your filter because then you have the $(element).val() method you can use to evaluate actual universal characters.

Then you can filter out any NON digits using a regex like:

replace(/[^0-9]/g,'');

This takes care of all issues like shift and paste problems because there is always a keyup and so the value will always be evaluated (unless javascript is turned off).

So... to turn this into JQuery... Here is a little unfinished plugin I'm writing, it is called inputmask and will support more masks when finished. For now it has the digits mask working.

Here it goes...

/**
 * @author Tom Van Schoor
 * @company Tutuka Software
 */
(function($) {
  /**
   * @param {Object}
   * $$options options to override settings
   */
  jQuery.fn.inputmask = function($$options) {
    var $settings = $.extend( {}, $.fn.inputmask.defaults, $$options);

    return this.each(function() {
      // $this is an instance of the element you call the plug-in on
      var $this = $(this);

      /*
       * This plug-in does not depend on the metadata plug-in, but if this
       * plug-in detects the existence of the metadata plug-in it will
       * override options with the metadata provided by that plug-in. Look at
       * the metadata plug-in for more information.
       */
      // o will contain your defaults, overruled by $$options,
      // overruled by the meta-data
      var o = $.metadata ? $.extend( {}, $settings, $this.metadata()) : $settings;

      /*
       * if digits is in the array 'validators' provided by the options,
       * stack this event handler
       */
      if($.inArray('digits', o.validators) != -1) {
        $this.keyup(function(e) {
          $this.val(stripAlphaChars($this.val()));
        });
      }

      /*
       * There is no such things as public methods in jQuery plug-ins since
       * there is no console to perform commands from a client side point of
       * view. Typically only private methods will be fired by registered
       * events as on-click, on-drag, etc... Those registered events could be
       * seen as public methods.
       */

      // private method
      var stripAlphaChars = function(string) {
        var str = new String(string); 
        str = str.replace(/[^0-9]/g, ''); 
        return str;
      }

    });
  };

  // static public functions
  //jQuery.fn.inputmask.doSomething = function(attr) {

  //};

  // static public members
  //jQuery.fn.inputmask.someStaticPublicMember;

  // some default settings that can be overridden by either $$options or
  // metadata
  // If you need callback functions for the plug-in, this is where they get
  // set
  jQuery.fn.inputmask.defaults = {
    validators : []
  };
})(jQuery);

To use it just do:

$('#someElementId').inputmask({
  validators: ['digits','someOtherNotYetImplementedValidator']
});

The 'someOtherNotYetImplementedValidator' is just there to show how this can be expanded for extra future masks/validators. You can add it or leave it out, it doesn't break anything ;-)

Appologies for the extra clutter of comments, I'm using a template I created for the guys here at work.

Hope this helps, Cheers


Updated solution for a better user experience, that addresses the copy+paste issue and replaces the deprecated keyCode attribute:

HTML

<input type="tel">

jQuery

$('[type=tel]').on('change', function(e) {
  $(e.target).val($(e.target).val().replace(/[^\d]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
  keys = ['0','1','2','3','4','5','6','7','8','9']
  return keys.indexOf(event.key) > -1
})

Details:

First of all, input types:

number shows up/down arrows shrinking the actual input space, I find them ugly and are only useful if the number represents a quantity (things like phones, area codes, IDs... don't need them) tel provides similar browser validations of number without arrows

Using [number / tel] also helps showing numeric keyboard on mobile devices.

For the JS validation I ended up needing 2 functions, one for the normal user input (keypress) and the other for a copy+paste fix (change), other combinations would give me a terrible user experience.

I use the more reliable KeyboardEvent.key instead of the now deprecated KeyboardEvent.charCode

And depending of your browser support you can consider using Array.prototype.includes() instead of the poorly named Array.prototype.indexOf() (for true / false results)


You can use HTML5 validation on your text inputs by adding a pattern. No need to manually validate with regex or keyCodes.

<input type="text" pattern="[0-9.]+" />

$("input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = this.value.slice(0, -1);
});

Possible, but not as simple for inputs [type=number]...

The problem with [type="number"] is that we cannot only remove the invalid character at the end. The User Agents return an empty string whenever the input is invalid.

From the W3C HTML5 spec:

If the value of the element is not a valid floating point number, then set it to the empty string instead.

https://dev.w3.org/html5/spec-LC/number-state.html#number-state

This means we need a way to store the previous input value by hand.

So for number inputs, the solution would look like this:

$("input[type=number], input[type=text][pattern]").on("input", function () {
    if (!this.checkValidity())
        this.value = $(this).data("current-valid") || "";
    else
        $(this).data("current-valid", this.value);
});

Unfortunately, this will not work on IE and EDGE. We need to resort to the pattern solution above for these browsers. However, you can still use number inputs with this simple polyfill.

$("input[type=number]").attr("type", "text").attr("pattern", "[0-9.]+");

I have combined all the answers in one and come up with the following code:

jQuery('#input_id', function(e){
    // Allow: backspace, delete, tab, escape, enter
    if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
        // Allow: Ctrl+A
        (e.keyCode === 65 && e.ctrlKey === true) ||
        // Allow: Ctrl+C
        (e.keyCode === 67 && e.ctrlKey === true) ||
        // Allow: Ctrl+X
        (e.keyCode === 88 && e.ctrlKey === true) ||
        // Disallow several dots (allow 190 only if no dots found)
        (e.keyCode === 190 && jQuery(this).val().indexOf('.') == -1) ||
        // Bug in some Android devices where it is always 229
        (e.keyCode === 229) ||
        // Allow: home, end, left, right
        (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();
    }
});

In addition the form should have autocomplete="off". Without this option you might have issues with auto-complete algorithms on mobile devices.


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()"/>

This jQuery code filters out characters typed while Shift, Ctrl or Alt is held down.

$('#AmountText').keydown(function (e) {
    if (e.shiftKey || e.ctrlKey || e.altKey) { // if shift, ctrl or alt keys held down
        e.preventDefault();         // Prevent character input
    } else {
        var n = e.keyCode;
        if (!((n == 8)              // backspace
        || (n == 46)                // delete
        || (n >= 35 && n <= 40)     // arrow keys/home/end
        || (n >= 48 && n <= 57)     // numbers on keyboard
        || (n >= 96 && n <= 105))   // number on keypad
        ) {
            e.preventDefault();     // Prevent character input
        }
    }
});

You can try the HTML5 number input:

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

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


Simple way to check that enter value is numeric is:

var checknumber = $('#textbox_id').val();

    if(jQuery.isNumeric(checknumber) == false){
        alert('Please enter numeric value');
        $('#special_price').focus();
        return;
    }

I think it will help everyone

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

Here is two different approaches:

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

APPROACH 1:

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

APPROACH 2:

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


This would maintain the previous value in case a non-numeric character is added.

$(document).on('input', '.digit-input', function() {
    var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';
    var newVal = this.value.replace(/[^0-9]/g, '');
    this.value = newVal != '' ? newVal : prevVal;
    $(this).attr('ov', this.value);
});

_x000D_
_x000D_
$(document).on('input', '.digit-input', function() {_x000D_
     var prevVal = $(this).attr('ov') ? $(this).attr('ov') : '';_x000D_
     var newVal = this.value.replace(/[^0-9]/g, '');_x000D_
     this.value = newVal != '' ? newVal : prevVal;_x000D_
     $(this).attr('ov', this.value);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<input type="text" class="digit-input">
_x000D_
_x000D_
_x000D_


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;
});

Inline:

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

Unobtrusive style (with jQuery):

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


You can try the HTML5 number input:

<input type="number" placeholder="enter the number" min="0" max="9">

This input tag element would now take value only between 0 to 9 as min attribute is set to 0 and max attribute is set to 9.

for more information on visit http://www.w3schools.com/html/html_form_input_types.asp


Here is way with regular expression:

$('input').bind('keypress', function (event) {
var regex = new RegExp("^[0-9]+$");
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
   event.preventDefault();
   return false;
}

});

https://jsfiddle.net/astrapi69/qbk2vjty/1/

And you can change the regular expression to anything else if you want to restrict other characters then numbers.


Another approach is below. This will take care of pasting also. [it is for alpha-numeric validation]

//Input Validation
var existingLogDescription = "";

$('.logDescription').keydown(function (event) {
    existingLogDescription = this.value;

});


$('.logDescription').keyup(function () {
    if (this.value.match(/[^a-zA-Z0-9 ]/g)) {
        alert("Log Description should contain alpha-numeric values only");
        this.value = this.value.replace(/[^a-zA-Z0-9 ]/g, '');
        this.value = existingLogDescription;
    }
});

I'm using in this form. Seems correct to me allow keys like home, end, shift and ctrl, with the drawback of the user to can print special chars:

$("#busca_cep").keydown(function(event) {
    if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 13 || event.keyCode == 16 || event.keyCode == 36 || event.keyCode == 35) {
        if (event.keyCode == 13) {
            localiza_cep(this.value);
        }
    } else {
        if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
            event.preventDefault(); 
        }   
    }
});

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();

Simpler one for me is

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

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.


To elaborate a little more on answer #3 I'd do the following (NOTE: still does not support paste oprations through keyboard or mouse):

$('#txtNumeric').keypress(
            function(event) {
                //Allow only backspace and delete
                if (event.keyCode != 46 && event.keyCode != 8) {
                    if (!parseInt(String.fromCharCode(event.which))) {
                        event.preventDefault();
                    }
                }
            }
        );

function Numbers(e)
{
    if($.browser.msie)
    {
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
        else
            return false;
    }
    else
    {
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
        else
            return false;
    }
}

I hope this will work on all browsers.


This answer was perfect, but we can even make it better and more powerful by combining it with the jQuery.Validation plugin.

By using the number() method, we can develop something like this:

$('.numberOnly').keydown(function (event) { 
  if ((!event.shiftKey && !event.ctrlKey && !event.altKey) && 
    ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105))) 
  // 0-9 or numpad 0-9, disallow shift, ctrl, and alt 
  { 
    // check textbox value now and tab over if necessary 
  } 
  else if (event.keyCode != 8 && event.keyCode != 13 && event.keyCode != 46 && event.keyCode != 37 
    && event.keyCode != 39 && event.keyCode != 9 && event.keyCode != 109 
    && event.keyCode != 189 && event.keyCode != 110 && event.keyCode != 190) 
  // not backsapce (8), enter (13), del (46), left arrow (37), right arrow (39), tab (9), negetive sign (- : 109, 189), or point (. : 110, 190) 
  { 
    event.preventDefault(); 
  } 
  // else the key should be handled normally 
}); 
// _____________________________________________
jQuery.validator.setDefaults({ 
  debug: true, 
  success: "valid" 
}); 
// _____________________________________________
$(document).ready(function(){ 
  $('#myFormId').validate({ 
    rules: { 
      field: { 
        required: true, 
        number: true 
      } 
    } 
  }); 
}); 

So, any Textbox in the "#myFormId" form, with "numberOnly" class, accept only number including decimal, float, and even negative number. Voila :)

PS: In my case, for some reason I used jQuery.validator.addMethod() instead of .validate():

jQuery.validator.addMethod("numberOnly", function (value, element) { 
var result = !isNaN(value); 
return this.optional(element) || result; 
}, jQuery.format("Please enter a valid number.")); 

(it works fine inside my ASP.NET MVC 3 project + unobtrusive JavaScript validation, hooooooooray!)


Need to make sure you have the numeric keypad and the tab key working too

 // 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)) {

                }
                else {
                    event.preventDefault();
                }
            }

Just need to apply this method in Jquery and you can validate your textbox to just accept number only.

function IsNumberKeyWithoutDecimal(element) {    
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp); 
}

Try this solution here


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.

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.


It may be overkill for what you are looking for, yet I suggest a jQuery plugin called autoNumeric() - it is great!

You can limit to only numbers, decimal precision, max / min values and more.

http://www.decorplanit.com/plugin/


I had a problem with the top-answer. It doesn't include the numerical keypad and if one presses shift+number the special-signs shouldn't be displayed either.. but this solution doesn't take care of it.

The best link I've found in this thread was this: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values

I'm new to stackoverflow so I don't know if I can just edit the better solution into the top-post.


try it within html code it self like onkeypress and onpast

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

Use below simple jQuery to allow only numeric characters in a tetbox. You do not need to filter all the special characters manually so there is no danger of missing some special char. This will allow only numbers 0-9: (Place below code in document ready and change the class name as per your numeric text fields class name.)

//Event of data being keyed in to textbox with class="numericField".
$(".numericField").keyup(function() {
    // Get the non Numeric char that was enetered
    var nonNumericChars = $(this).val().replace(/[0-9]/g, '');                                  
    // Now set the value in text box 
    $(this).val( $(this).val().replace(nonNumericChars, ''));    

});

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...


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
        }
    }

You can do the same by using this very simple solution

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

I referred to this link for the solution. It works perfectly!!!


function validate_profile(frmid) {
    var form = $('#' + frmid);
    var error = $('.alert-danger', form);
    var success = $('.alert-success', form);
    form.validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block', // default input error message class
        focusInvalid: true, // do not focus the last invalid input
        ignore: "",
        rules: {
            contact_no: {
                required: true,
                minlength: 10,
                maxlength: 10,
                number: true
            }, email_id: {
                required: true,
                email: true
            }
        },
        invalidHandler: function (event, validator) { //display error alert on form submit   
            success.hide();
            error.show();
            Metronic.scrollTo(error, -7000);
        },
        highlight: function (element) { // hightlight error inputs
            $(element)
                    .closest('.form-group').addClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').removeClass('has-success'); // set success class to the control group
        },
        unhighlight: function (element) { // revert the change done by hightlight
            $(element)
                    .closest('.form-group').removeClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').addClass('has-success'); // set success class to the control group
            error.hide();
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error');
            label.closest('.form-group').addClass('has-success');
        },
        submitHandler: function (form) {
            success.show();
            error.hide();
            form.submit();
        }
    });
}

$(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


I came to 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

None of the answers worked in my case so I made a little change in the accepted answer to make it work for Dynamically added elements.

Enjoy :

var inputFilter = function (elem, cb) {
    /*
    *    /^-?\d*$/               restricts input to integer numbers
    *    /^\d*$/                 restricts input to unsigned integer numbers
    *    /^[0-9a-f]*$/i          restricts input to hexadecimal numbers
    *    /^-?\d*[.,]?\d*$/       restricts input to floating point numbers (allowing both . and , as decimal separator)
    *    /^-?\d*[.,]?\d{0,2}$/   restricts input to currency values (i.e. at most two decimal places)
    */
    bdy.on('input keydown keyup mousedown mouseup select contextmenu drop', elem, function () {
        if (cb(this.value)) {
            this.oldValue = this.value;
            this.oldSelectionStart = this.selectionStart;
            this.oldSelectionEnd = this.selectionEnd;
        } else if (this.hasOwnProperty('oldValue')) {
            this.value = this.oldValue;
            this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
        }
    });
};

Usage :

inputFilter('#onlyDigitsInput', function (val) {
    return /^\d*$/.test(val);
});

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(); 
        }   
    }
});

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)');

This is why I recently wrote to accomplish this. I know this has already been answered but I'm leaving this for later uses.

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();
    }
});

Try this one

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

put a class in input text and name it only_numbers

put the jquery code in the page

$(document).ready(function() {
    $('.only_numbers').keyup(function() {
        var numbers = $(this).val();
        $(this).val(numbers.replace(/\D/, ''));
    });
});

have fun :-)


/**
Makes the textbox to accept only numeric input
*/

(function($) {
    $.fn.allowOnlyNumeric = function() {

        /**
        The interval code is commented as every 250 ms onchange of the textbox gets fired.
        */

        //  var createDelegate = function(context, method) {
        //      return function() { method.apply(context, arguments); };
        //  };

        /**
        Checks whether the key is only numeric.
        */
        var isValid = function(key) {
            var validChars = "0123456789";
            var validChar = validChars.indexOf(key) != -1;
            return validChar;
        };

        /**
        Fires the key down event to prevent the control and alt keys
        */
        var keydown = function(evt) {
            if (evt.ctrlKey || evt.altKey) {
                evt.preventDefault();
            }
        };

        /**
        Fires the key press of the text box   
        */
        var keypress = function(evt) {
            var scanCode;
            //scanCode = evt.which;
            if (evt.charCode) { //For ff
                scanCode = evt.charCode;
            }
            else { //For ie
                scanCode = evt.keyCode;
            }

            if (scanCode && scanCode >= 0x20 /* space */) {
                var c = String.fromCharCode(scanCode);
                if (!isValid(c)) {
                    evt.preventDefault();
                }
            }
        };

        /**
        Fires the lost focus event of the textbox   
        */
        var onchange = function() {
            var result = [];
            var enteredText = $(this).val();
            for (var i = 0; i < enteredText.length; i++) {
                var ch = enteredText.substring(i, i + 1);
                if (isValid(ch)) {
                    result.push(ch);
                }
            }
            var resultString = result.join('');
            if (enteredText != resultString) {
                $(this).val(resultString);
            }

        };

        //var _filterInterval = 250;
        //var _intervalID = null;

        //var _intervalHandler = null;

        /**
        Dispose of the textbox to unbind the events.
        */
        this.dispose = function() {
            $(this).die('change', onchange);
            $(this).die('keypress', keypress);
            $(this).die('keydown', keydown);
            //window.clearInterval(_intervalHandler);
        };

        $(this).live('change', onchange);
        $(this).live('keypress', keypress);
        $(this).live('keydown', keydown);
        //_intervalHandler = createDelegate(this, onchange);
        //_intervalID = window.setInterval(_intervalHandler, _filterInterval);
    }
})(jQuery);

The above $ plugin is written from the AjaxControlToolkit filter textbox extender.js.

However one behavior is not borrowed from the AjaxControlToolkit is that when the user copies and pastes any non-numeric value then the onchange event fires up and text box eats up the values. I went through the code and found out for this onchange was called after every 250ms, which is a performance hit, hence commented that part.


Use the jquery numeric value. Below function allows for decimal and numeric values.
Example: $("#inputId").numeric({ allow: "." });


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


If you have to solve diacritics and special characters, try to use this:

$(this).on( 'keypress', function( e )
{
    // Ensure that it is a number and stop the keypress
    if (e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) {
        e.preventDefault();
    }
});  

$(document).on("keypress", ".classname", function(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
});

There are so many good answers to doing it with java Script or jQuery here.

I will add a very easy way to archive this using just HTML5.

<input type="number" name="quantity" min="0" max="9">

Check if decimal point already used:-

        // Stop: Multiple decimal points
        if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
            e.preventDefault(); 

The SIMPLEST solution to this is within your html form code add:

<input type="number"

If it's a php form then add:

$data = array(
        'type' => 'number',

Both of these

  1. stops the user from typing a comma
  2. stops the user from pasting a comma (it pastes the number but strips the comma)

Refactored the accepted answer so that comments no longer need to used because I hate comments. Also this is easier to test with jasmine.

    allowBackspaceDeleteTabEscapeEnterPress: function(event){
    return ($.inArray(event.keyCode, [46, 8, 9, 27, 13, 190]) >= 0);
},
allowContorlAPress: function(event){
    return (event.keyCode == 65 && event.ctrlKey === true)
},
allowHomeEndLeftRightPress: function(event){
    return (event.keyCode >= 35 && event.keyCode <= 39)
},
theKeyPressedIsEditRelated: function (event) {
    return (this.allowBackspaceDeleteTabEscapeEnterPress(event)
            || this.allowContorlAPress(event)
            || this.allowHomeEndLeftRightPress(event));
},
isNotFromTheNumKeyPad: function (event) {
    return (event.keyCode < 96 || event.keyCode > 105);
},
isNotFromTopRowNumberKeys: function (event) {
    return (event.keyCode < 48 || event.keyCode > 57);
},
theKeyIsNonNumeric: function (event) {
   return (event.shiftKey
           || (this.isNotFromTopRowNumberKeys(event)
                && this.isNotFromTheNumKeyPad(event)));
},
bindInputValidator: function(){
    $('.myinputclassselector').keydown(function (event) {
        if(this.validateKeyPressEvent(event)) return false;
    });
},
validateKeyPressEvent: function(event){
    if(this.theKeyPressedIsEditRelated(event)){
        return;
    } else {
        if (this.theKeyIsNonNumeric(event)) {
            event.preventDefault();
        }
    }
}

$(document).ready(function()
{
    $("#textBoxId").bind("change",checkInput);
});

function checkInput()
{
    // check if $('#textBoxId').val() is under your constraints
    // then change its value, removing the last character
    // since this event will be called each time you
    // type a character
}

add below code in document.ready

    $('.class of text box').keyup(function () 
    {
    this.value = this.value.replace(/[^0-9]/g, '');
    });  

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to numeric

How to convert entire dataframe to numeric while preserving decimals? What's the difference between integer class and numeric class in R IsNumeric function in c# How to compare numbers in bash? Right way to convert data.frame to a numeric matrix, when df also contains strings? angularjs: allows only numbers to be typed into a text box How to convert Varchar to Double in sql? SQL Server : error converting data type varchar to numeric How do I convert certain columns of a data frame to become factors? How to create a numeric vector of zero length in R