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

1 2
3
0

Refactored the accepted answer so that comments no longer need to used. 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();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is for alpha-numeric validation and will take care of pasting also:

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

Comments

0

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.

Comments

0

There are so many good answers to doing it with JavaScript 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">

Comments

0

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/, ''));
    });
});

Comments

0

Allow single decimal and numeric only, single line:

$(document).on("input", "#bill_amount", function() {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
    // Remove extra dots by (/(\..*)\./g, '$1');
});

Comments

0

Short answer:

$('#mobile_number').on('input', function() {
            // Remove non-numeric characters
            this.value = this.value.replace(/\D/g, '');
            if (this.value.length > 8) {
                this.value = this.value.slice(0, 8);
            }
});

Comments

0

This code ensures that the user can only type numeric characters (0–9) into input fields with the class .classname. All other keys (letters, symbols) are blocked:

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

Comments

-1

Use the jQuery numeric value. Below function allows for decimal and numeric values.
Example:

$("#inputId").numeric({ allow: "." });

Comments

-2

This will work on all browsers:

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

1 Comment

Could you (or perhaps a fellow user through a comment) elaborate on this answer?
1 2
3

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.