views:

23593

answers:

13

I am creating a web page where I have a 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 make it using jquery??

Thanks

+1  A: 

Check regular-expression-matching-in-jquery

Macarse
+14  A: 

Have a look at this plug-in. This is another one.

This is a link if you want to build it yourself.

kgiannakakis
http://www.texotela.co.uk/code/jquery/numeric/ this one works for me :) thanks
Prashant
+6  A: 
$(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

Ivarska
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 Moore
Ivarska
Try pressing Shift + 8 for instance - your validation will let * get in
Anton
This is nice.Would be much better,If it handles the Shift key+Numbers (Special chars like !@#$%^..)
Shyju
+1  A: 

You can use this Javascript function:

function maskInput() {
     var key_code = window.event.keyCode;
     var oElement = window.event.srcElement;
     if (!window.event.shiftKey && !window.event.ctrlKey && !window.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 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()"/>
karim79
+6  A: 

Keep in mind that you cannot rely on client-side validation - you also need to validate on the server in case the user has JS turned off, or isn't using a JS compatible browser.

ck
+4  A: 

Also, keep in mind that the user can bypass any key press validation by right clicking the textbox and pasting in whatever they want from the clipboard.

Jim
+2  A: 

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();
                }
            }
Coppermill
+2  A: 

You could just use a simple JS regex to test for purely numeric characters:

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

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

TheDeveloper
A: 

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();
                    }
                }
            }
        );
Damiano
+7  A: 

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, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

You can then attach it to your control by doing:

$("#yourTextBoxName").ForceNumericOnly();
Kelsey
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?
Volmar
+5  A: 

Not using JQuery but simple and just using one javascript function
Use javascript function isNaN

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

@GalacticCowboy
Here is the edited sample to don't include any jquery:

if (isNaN(document.getElementById('inputid').val()))
Amr ElGarhy
Well... "Not using JQuery" except for the part of your example that is using JQuery...
GalacticCowboy
+1 cause this is a real kick-ass! only digits way! ;-)
aSeptik
A: 

Hey, me too!

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

you could also use this JQuery plugin Jquery alphaNumeric,i found it to be really great.check it here http://www.itgroup.com.ph/alphanumeric/

Layinka