How to allow only numeric (0-9) in HTML inputbox using jQuery?
Asked Answered
B

69

982

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?

Bullis answered 15/6, 2009 at 9:22 Comment(19)
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.Moersch
You could also use this jQuery plugin, jQuery alphaNumeric. I found it to be really great.Extrusion
This (jQuery numeric plugin) one works fine and has some neat features but you might have to adjust it a little bit for your needs and IE support.Preside
have you considered html5? <input type="number" />. with min and max attributes you can restrict input tooScholarship
You can use javascript but you'll have to keep in mind the additional javascript's performance hit on the processor of a poor phone. I had this issue and solved it with a <select> Since you just need 0-9? It's not crazy to use a select dropdown menu for that.Stockinet
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.Liver
Refer my answer #995683Crashaw
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.Unbacked
@Scholarship 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-numberForenamed
Are you sure you need jQuery for this? You can use the HTML5 pattern attribute on an input to restrict only numbers like so <input pattern="[0-9]+" />. I prefer this method because most browsers change the style of the input field when <input type="number" />Whichsoever
possible duplicate of jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)Convenience
@Moersch - Javascript being on/off is irrelevant. You must always validate on the server.Shrine
@WizLiz can you explain what exactly doesn't work for you?Gile
@Gile I've tried the included code snipet in the accepted answer and as stated in th boutny, I still manage to input special characters that are not numeric. Also when I try to press shift + a number (above the letters) nothing happens in the input.Pertain
@WizLiz, Which browser[+version]/os? Did you enter the char or did you use ctrl+v?Gile
@Gile lastest version of chrome though I've had the same issue with MS Edge, no pasting involved. Just regular input on the keyboard.Pertain
I've down voted this question because you're asking us to write code for you. What have you actually tried?Kieger
@Scholarship That doesn't actually restrict what you type in just the numbers you can click up and down to.Circinus
Does this answer your question? Is there a float input type in HTML5?Ignoramus
K
1362

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.

Kook answered 15/6, 2009 at 9:22 Comment(25)
Thanks! event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 if you want decimalsOptime
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)Rouault
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 !@#$%^&*()Hagood
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.Rouault
Also add event.keyCode==110 to allow decimals from the numeric keypad.Herring
You may also want to allow for function keys like F5 for example to refresh the pageBircher
There is a problem with TexoTela numeric plugin. It disables "onchange" event for textbox. This issue was reported on gitHub a year ago and there is no response till now...Incandescent
@bažmegakapa Don't we need to allow Backspace and Delete keys?Crashaw
@Nipzz The only issue I ran into with Macs was to make ⌘A work on Mac, I had to change (event.keyCode == 65 && event.ctrlKey === true) to (event.keyCode == 65 && (event.ctrlKey === true || event.metaKey === true ))Heisser
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.Unbacked
I added event.keyCode != 116 && (event.keyCode != 86 && event.ctrolKey === true) && (event.keyCode != 67 && event.ctrolKey === true) to allow for F5 (and Ctrl-F5) for page refreshing, Ctrl-C, Ctrl-V because my users would have complained.. :-)Ivyiwis
How does the edit must made a moment ago address the problem? I'm not convinced it's a valid edit.Mcghee
Add this // Allow: . dot for decimals (event.keyCode == 110 || event.keyCode == 190)Caladium
How can i avoid 0 value i want 1 to 9, 10 is acceptable but single 0 should not be there.Nuzzi
With thanks to all, I wrote another with min and max range. You could see in: #2013729 @miniQuark please tell me if you have any point.Conferva
I agree with @Unbacked about the azerty keyboards. On those keyboards you need to press shift. When using jQuery you can use the keypress eventhandler. For example: $('#nummer').keypress(function (event) { console.log('keypress: ' + event.which); if (!isNumber(event.which)) { event.preventDefault(); } }); function isNumber(characterCode) { var isNumber = false; if (characterCode >= 48 && characterCode <= 57) { isNumber = true; } return isNumber; }Correggio
add event.keyCode == 40 for Up buttonIntendance
Works like a charm in firefox but in chrome you still can type this char ^ and also ´ this (at least on a qwertz-keyboard) - any idea how to prevent that?Capreolate
Related to the upper issues and some additional needed features, how about this plugin: github.com/customd/jquery-number . Demo: texotela.co.uk/code/jquery/numeric and opensource.teamdf.com/number/examples/demo-as-you-type.html It has custom validation of a string value or can be attached to a component. It support live auto formatting during typing, customizable length of fraction digits and rounding, changing the coma symbol and the thousands separator symbol. It pretty sums everything from the discussed functionality here plus some useful extrasGrano
if ctrl+v a invalid char, the script do not detect.Licketysplit
Don't take it. It doesn't prevent key combination, like alt + number, spanish accent key... Better answer: https://mcmap.net/q/47590/-allow-only-numbers-to-be-typed-in-a-textbox-duplicate. Here is screenshot of error: http://img10.lostpic.net/2016/06/12/8dd58e87f2310edb79c25d8571fb6261.pngManard
This for protected multiple dot if (e.keyCode == 190 && $(this).val().indexOf(".") > -1) { return false; }Teenyweeny
however we can still copy text from any text source and paste it in textboxHomoeroticism
Excellent post. For absolute clarity and to help those new to jQuery, perhaps make it clear that the "installation" phase should be performed within $(document).ready(function() { // Restrict input to digits by using a regular expression filter. $("#myTextBox").inputFilter(function(value) { return /^\d*$/.test(value); }); });Cooler
This is not working in my case. Allow 1-99 value, minimum 1 and maximum 99, maxlength 2, negative value not allow, only numeric values (No symbol and alphabet). BTW Thanks for asking this question.Ninos
W
200

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();
Wayfarer answered 15/6, 2009 at 9:22 Comment(10)
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?Wendelina
Keys "Home", "End" is not working too. This is a better solution which Peter suggested: west-wind.com/weblog/posts/2011/Apr/22/…Concurrence
Why is there a return this.each(function() ?Negrillo
@Negrillo - so you can call .ForceNumericOnly() on multiple objects. For example... $("input[type='text']").ForceNumericOnly()Secretarial
@Negrillo 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()Koumis
Beautifull but please add key == 13 || to make sure Enter is allowed, for form submital and suchGleich
if i want to allow negative number and passing the '-' sign key code which is different for different browser. Then its not working (key==173||key==189) //173 ='-' in chrome, 189='-' in mozillaQuick
Thnx. Its possible to control only one decimal point?Eros
and a max value?Eros
Thx, but it allows some characters like á, éProkofiev
G
180

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">
Gustafsson answered 15/6, 2009 at 9:22 Comment(13)
This moves the caret to the end even if the user is pressing left arrow key.Cascarilla
@phrogz, try this: onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')".Gustafsson
This works perfectly, and prevents Shift+number unlike those above.Moonrise
Almost perfect - leading minus signs are lost. It's beyond me though how to preserve one if it is there.Salamander
This solves the stated problem: only allow 0-9. If you want to allow a leading minus sign, the solution cannot be so simple. A nice option is to store the previous value and revert if the new one is invalid: onkeyup="if (/^-?\d*$/.test(this.value)){ this.oldValue = this.value; } else { this.value = this.oldValue || ''; }".Gustafsson
I find the inline method to be the cleanest. Thanks!Schoolboy
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).Dowsabel
@Dowsabel 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.Gustafsson
You could modify to /[^0-9]|^0+(?!$)/g to prevent leading series of zero.Irretentive
Can this be modified to allow a decimal / full stop?Lashundalasker
To allow any valid decimal number (using JavaScript's built in number validation), try this: onkeyup="if (isNaN(parseFloat(this.value))) { this.value = this.oldValue || ''; } else { this.oldValue = this.value; }".Gustafsson
best answer as it permits every kind of keyboardRecalescence
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
S
108

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.
Stink answered 15/6, 2009 at 9:22 Comment(5)
I feel like this is a much more robust (and simpler) solution than the accepted answer.Amaryl
Even simpler if using replace(/\D/g, '')Prolong
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
I would suggest using this.value = Number(this.value.replace(/\D/g, ''));Wieland
Good answer, allows to easily toggle whether an input is numeric or not by toggling classGeorgena
V
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();
    }
Vasquez answered 15/6, 2009 at 9:22 Comment(3)
See my answer for an implementation of this approach.Gustafsson
wouldn't it take less processor time to check for a numerical keypress rather then checking a regular expression?Revulsive
This would not prevent pasting letters with CTRL+V right?Ranged
S
72

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, '');
  });
Sukkoth answered 15/6, 2009 at 9:22 Comment(3)
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 happenPertain
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, ''); });Mcpeak
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.Destinydestitute
P
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

Pollywog answered 15/6, 2009 at 9:22 Comment(4)
Well... "Not using JQuery" except for the part of your example that is using JQuery...Consolata
document.getElementById('inputid').val() dude.. that's still jquery. .val() is a jquery thing. use .valueStereopticon
Using isNaN alone is a bad idea because of JavaScript type coercion.Polymath
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
S
34
$(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

Smother answered 15/6, 2009 at 9:22 Comment(4)
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?Puccini
@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.Smother
Try pressing Shift + 8 for instance - your validation will let * get inLobito
This is nice.Would be much better,If it handles the Shift key+Numbers (Special chars like !@#$%^..)Hobbledehoy
S
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;
});
Stonewall answered 15/6, 2009 at 9:22 Comment(1)
Nice, elegant and useful code! Thanks. But you must add keyup and keydown events.Sensate
R
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.

Retrospect answered 15/6, 2009 at 9:22 Comment(3)
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.Asel
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!Retrospect
@Retrospect Thank you so much for this. Quickest and easiest answer! Top answer in my opinion.Ticktock
F
26

Simpler one for me is

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});
Ferromagnetism answered 15/6, 2009 at 9:22 Comment(1)
Just need to be sure you use this.value.replace(/[^0-9\.]/g,''); to include OP's requirements of 0-9Sudd
D
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. It works perfectly!!!

Delgadillo answered 15/6, 2009 at 9:22 Comment(3)
Maybe this is better /\d|\./ to allow . decimal numbersTolan
This works perfect in crome. But not in Mozilla FireFoxAmylolysis
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
E
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.

Eyrie answered 15/6, 2009 at 9:22 Comment(2)
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
@transformer try this <input type="number" pattern="[0-9]+([\.,][0-9]+)?" step="0.01">Eyrie
N
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.

Nodababus answered 15/6, 2009 at 9:22 Comment(1)
this still allows comma'sVincent
R
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
        }
    }
Romonaromonda answered 15/6, 2009 at 9:22 Comment(3)
hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .Dingdong
Great solution. Add keyCode 9 as well to allow TABCharacharabanc
Thank you for your Solution. exact and clear.Prosecution
L
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">
Loaf answered 15/6, 2009 at 9:22 Comment(1)
Can you explain to me what : ] you used? Because I did not understand it and thank you for the codeUsherette
P
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)');
Pimental answered 15/6, 2009 at 9:22 Comment(0)
C
10

If have a smooth OneLiner:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >
Clubfoot answered 15/6, 2009 at 9:22 Comment(1)
Great solution but is onkeypress not depreciated? Replacing this with onkeydown actually causes a problem, it does not allow a backspace?Lettyletup
D
10

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">
Decompensation answered 15/6, 2009 at 9:22 Comment(0)
R
8

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
Rocco answered 15/6, 2009 at 9:22 Comment(1)
Hey i am using this but what i am really looking is to allow him dot like 1.2 or 3.455 like thatAlesha
K
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()"/>
Kreager answered 15/6, 2009 at 9:22 Comment(1)
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 .Grimaldo
S
7

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);
});
Strychnine answered 15/6, 2009 at 9:22 Comment(0)
C
7

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 ;
  })
Colyer answered 15/6, 2009 at 9:22 Comment(1)
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;Parvenu
L
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));
});
Laugh answered 15/6, 2009 at 9:22 Comment(0)
B
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;
    }
});
Bimbo answered 15/6, 2009 at 9:22 Comment(1)
does this ensure $ and then + - as first or first/second characters and then only 1 decimal point?Episcopal
V
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(); 
        }   
    }
});
Valuer answered 15/6, 2009 at 9:22 Comment(0)
A
6

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;
        }
    });
});
Acerb answered 15/6, 2009 at 9:22 Comment(0)
R
6

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();
    }
});
Recommit answered 15/6, 2009 at 9:22 Comment(0)
P
5

You can use the following code.

<input type="text" onkeypress="return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57">
Paroxysm answered 15/6, 2009 at 9:22 Comment(1)
Does not prevent pasting invalid content though.Mcfarlane
V
5

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

Vogeley answered 15/6, 2009 at 9:22 Comment(0)
S
5

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

Subtemperate answered 15/6, 2009 at 9:22 Comment(0)
M
5

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;
    }
Messner answered 15/6, 2009 at 9:22 Comment(0)
C
5

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

Coughlin answered 15/6, 2009 at 9:22 Comment(0)
K
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 ;)

Kerril answered 15/6, 2009 at 9:22 Comment(0)
E
5

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();
                }
            }
Enneastyle answered 15/6, 2009 at 9:22 Comment(0)
C
4

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.]+");
Cathead answered 15/6, 2009 at 9:22 Comment(0)
H
4

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();
    }
});  
Higgs answered 15/6, 2009 at 9:22 Comment(0)
B
4

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

Bootjack answered 15/6, 2009 at 9:22 Comment(4)
Good points about key code compatibility issues and checking the field value. But all we need is this: onkeyup="this.value=this.value.replace(/\D/g,'')".Gustafsson
Very true Patrick, it can be done in a one-liner. But for my purposes I needed a validator plugin so I could register more validators like "digits" and "ValidCreditCard", etc...Bootjack
@Patrick Fisher: It's a good idea. The main problem is that the cursor will move to the end with every keystroke, rendering the arrow keys useless. Try $("#inputfield").keypress(function(e) { if (e.which < 48 || e.which > 57) e.preventDefault(); });Aerugo
@Aerugo See my comment above, where I suggest if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'') so the value is only changed (and the cursor jumps to the end) if there is an invalid character. That way, you can still use arrow keys. You can also enter numbers in the middle without the cursor moving.Gustafsson
C
3

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)

Concave answered 15/6, 2009 at 9:22 Comment(0)
S
3

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.

Sunstone answered 15/6, 2009 at 9:22 Comment(1)
This was the only code that worked on IE to prevent chars for input number. I also added a validation for maxlength that doesn't work in some browsers. (Ex. if (!regex.test(key) || this.value.length == this.maxLength) )Proceeding
F
3

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.

Felicity answered 15/6, 2009 at 9:22 Comment(0)
N
3

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
        }
    }
});
Natch answered 15/6, 2009 at 9:22 Comment(0)
H
3

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();
                    }
                }
            }
        );
Hardner answered 15/6, 2009 at 9:22 Comment(0)
M
2

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

$("#txt").on("keypress",function(e){
  console.log("Entered Key is " + e.key);
  switch (e.key)
     {
         case "1":
         case "2":
         case "3":
         case "4":
         case "5":
         case "6":
         case "7":
         case "8":
         case "9":
         case "0":
         case "Backspace":
             return true;
             break;

         case ".":
             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.
             {
                 return true;
             }
             else
             {
                 return false;
             }
             break;

         default:
             return false;
     }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Enter Value
<input id="txt" type="text" />

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.

Markhor answered 15/6, 2009 at 9:22 Comment(0)
C
2

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/

Custodian answered 15/6, 2009 at 9:22 Comment(0)
V
2

add below code in document.ready

    $('.class of text box').keyup(function () 
    {
    this.value = this.value.replace(/[^0-9]/g, '');
    });  
Vaas answered 15/6, 2009 at 9:22 Comment(0)
N
2

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/

Neutral answered 15/6, 2009 at 9:22 Comment(0)
C
1

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)
Claudy answered 15/6, 2009 at 9:22 Comment(0)
N
1

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);
});
Niobic answered 15/6, 2009 at 9:22 Comment(0)
H
1

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

Hamill answered 15/6, 2009 at 9:22 Comment(0)
S
1
/**
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.

Sammiesammons answered 15/6, 2009 at 9:22 Comment(0)
C
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');
});
Cosmopolitan answered 15/6, 2009 at 9:22 Comment(0)
L
0

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

$(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);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="digit-input">
Lankford answered 15/6, 2009 at 9:22 Comment(0)
O
0
$(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;
});
Oxonian answered 15/6, 2009 at 9:22 Comment(0)
B
0

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">
Ballot answered 15/6, 2009 at 9:22 Comment(0)
L
0

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

$('input[name="number"]').keyup(function(e) {
    var float = parseFloat($(this).attr('data-float'));

    /* 2 regexp for validating integer and float inputs *****
        > integer_regexp : allow numbers, but do not allow leading zeros
        > 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
    *************************************************************************/
    var integer_regexp = (/[^0-9]|^0+(?!$)/g);
    var float_regexp = (/[^0-9\.]|^\.+(?!$)|^0+(?=[0-9]+)|\.(?=\.|.+\.)/g);

    var regexp = (float % 1 === 0) ? integer_regexp : float_regexp;
    if (regexp.test(this.value)) {
        this.value = this.value.replace(regexp, '');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" data-float="1" id="number" name="number" placeholder="integer">
<input type="text" data-float="0.1" id="number" name="number" placeholder="float">
Loran answered 15/6, 2009 at 9:22 Comment(0)
D
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/, ''));
    });
});

have fun :-)

Derisible answered 15/6, 2009 at 9:22 Comment(0)
R
0
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();
        }
    });
}
Rey answered 15/6, 2009 at 9:22 Comment(1)
please post with explanation.Tengdin
H
0

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.

Helbonnas answered 15/6, 2009 at 9:22 Comment(0)
R
0

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

});
Rescissory answered 15/6, 2009 at 9:22 Comment(0)
B
0

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();
        }
    }
}
Balbur answered 15/6, 2009 at 9:22 Comment(0)
D
0
$(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
}
Dynamism answered 15/6, 2009 at 9:22 Comment(0)
K
0

Check if decimal point already used:-

        // Stop: Multiple decimal points
        if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
            e.preventDefault(); 
Kaufmann answered 15/6, 2009 at 9:22 Comment(0)
C
0

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;
    }
});
Crashaw answered 15/6, 2009 at 9:22 Comment(0)
B
0

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(); 
        }   
    }
});
Blazonry answered 15/6, 2009 at 9:22 Comment(0)
J
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.

Jeb answered 15/6, 2009 at 9:22 Comment(0)
M
0
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);
});
Mallorie answered 15/6, 2009 at 9:22 Comment(0)
A
-1

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

Accomplishment answered 15/6, 2009 at 9:22 Comment(0)
P
-2
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.

Peaked answered 15/6, 2009 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.