980

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?

Nachshon Schwartz
  • 15,289
  • 20
  • 59
  • 98
djmzfKnm
  • 26,679
  • 70
  • 166
  • 227
  • 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. – cjk Jun 15 '09 at 09:50
  • 50
    have you considered html5? . with min and max attributes you can restrict input too – ZX12R Apr 11 '12 at 04:33
  • 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 – Gilly Jun 05 '12 at 14:51
  • 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. – Richard Jun 20 '12 at 08:08
  • Refer my answer http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery/12384598#12384598 – LCJ Sep 12 '12 at 09:01
  • 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. – MiniQuark Dec 12 '12 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. http://caniuse.com/#feat=input-number – Eric Mar 20 '13 at 13:53
  • Are you sure you need jQuery for this? You can use the HTML5 pattern attribute on an input to restrict only numbers like so ``. I prefer this method because most browsers change the style of the input field when `` – Daan May 29 '14 at 09:30
  • possible duplicate of [jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)](http://stackoverflow.com/questions/891696/jquery-what-is-the-best-way-to-restrict-number-only-input-for-textboxes-all) – Jim G. Nov 16 '14 at 01:59
  • 2
    @cjk - Javascript being on/off is irrelevant. You must _always_ validate on the server. – John Nov 05 '15 at 18:02
  • @WizLiz can you explain what exactly doesn't work for you? – Dekel Aug 04 '16 at 13:45
  • @Dekel 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. – WizLiz Aug 04 '16 at 13:47
  • @WizLiz, Which browser[+version]/os? Did you enter the char or did you use ctrl+v? – Dekel Aug 04 '16 at 13:51
  • @Dekel lastest version of chrome though I've had the same issue with MS Edge, no pasting involved. Just regular input on the keyboard. – WizLiz Aug 04 '16 at 13:59
  • I've down voted this question because you're asking us to write code for you. What have you actually tried? – kamoroso94 Aug 05 '16 at 07:27
  • @ZX12R That doesn't actually restrict what you type in just the numbers you can click up and down to. – azulBonnet Feb 16 '18 at 17:12
  • [This (jQuery numeric plugin)](http://plugins.jquery.com/project/Numeric) one works fine and has some neat features but you might have to adjust it a little bit for your needs and IE support. – Garry May 10 '11 at 14:51
  • You could also use this jQuery plugin, [jQuery alphaNumeric](http://www.itgroup.com.ph/alphanumeric/). I found it to be really great. – Layinka Oct 13 '10 at 10:32
  • Does this answer your question? [Is there a float input type in HTML5?](https://stackoverflow.com/questions/19011861/is-there-a-float-input-type-in-html5) – Braiam Jul 18 '22 at 14:58

68 Answers68

1361

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.

Kar.ma
  • 743
  • 6
  • 12
kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • 47
    Thanks! event.keyCode == 46 || event.keyCode == 8 || **event.keyCode == 190** if you want decimals – Michael L Watson Sep 16 '11 at 06:32
  • 9
    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) – Anthony Queen Jan 12 '12 at 14:06
  • 22
    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 !@#$%^&*() – Allen Rice Jan 18 '12 at 23:14
  • 6
    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. – Anthony Queen Jan 19 '12 at 18:34
  • Also add event.keyCode==110 to allow decimals from the numeric keypad. – Jon Crowell Mar 22 '12 at 16:32
  • You may also want to allow for function keys like F5 for example to refresh the page – Ruslans Uralovs Mar 22 '12 at 17:40
  • 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... – Episodex May 09 '12 at 09:56
  • @bažmegakapa Don't we need to allow Backspace and Delete keys? – LCJ Sep 12 '12 at 07:07
  • 3
    @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 )) – David Stinemetze Oct 10 '12 at 05:16
  • 149
    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. – MiniQuark Dec 12 '12 at 14:18
  • 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.. :-) – Ads Feb 05 '13 at 22:23
  • How does the edit must made a moment ago address the problem? I'm not convinced it's a valid edit. – Richard Sitze Aug 04 '13 at 16:04
  • 1
    Add this // Allow: . dot for decimals (event.keyCode == 110 || event.keyCode == 190) – Timothy Sep 09 '13 at 13:41
  • How can i avoid 0 value i want 1 to 9, 10 is acceptable but single 0 should not be there. – NoviceToDotNet Mar 14 '14 at 10:15
  • With thanks to all, I wrote another with min and max range. You could see in: http://stackoverflow.com/questions/2013229/jquery-numeric-textbox-with-min-and-max-ranges/25710687#25710687 @miniQuark please tell me if you have any point. – QMaster Sep 07 '14 at 13:32
  • 3
    I agree with @MiniQuark 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; }` – Luc Wollants Sep 26 '14 at 12:31
  • add `event.keyCode == 40` for Up button – Muxa Dec 05 '14 at 03:27
  • 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? – user2718671 Mar 02 '15 at 07:54
  • Related to the upper issues and some additional needed features, how about this plugin: https://github.com/customd/jquery-number . Demo: http://www.texotela.co.uk/code/jquery/numeric/ and http://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 extras – Vasil Popov Jun 24 '15 at 12:00
  • 1
    if ctrl+v a invalid char, the script do not detect. – Daniel Omine Jun 29 '15 at 09:41
  • 1
    Don't take it. It doesn't prevent key combination, like alt + number, spanish accent key... Better answer: [http://stackoverflow.com/a/7295864/3710490](http://stackoverflow.com/a/7295864/3710490). Here is screenshot of error: [http://img10.lostpic.net/2016/06/12/8dd58e87f2310edb79c25d8571fb6261.png](http://img10.lostpic.net/2016/06/12/8dd58e87f2310edb79c25d8571fb6261.png) – Valijon Jun 12 '16 at 16:28
  • This for protected multiple dot if (e.keyCode == 190 && $(this).val().indexOf(".") > -1) { return false; } – cloverink Oct 27 '16 at 11:59
  • however we can still copy text from any text source and paste it in textbox – Krunal Limbad Jun 14 '17 at 11:06
  • 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); }); }); – CJPN Jun 10 '19 at 14:39
  • 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. – Kamlesh Sep 20 '19 at 16:45
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();
Pawel Cioch
  • 2,895
  • 1
  • 30
  • 29
Kelsey
  • 47,246
  • 16
  • 124
  • 162
  • 2
    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 Aug 10 '10 at 09:39
  • 3
    Keys "Home", "End" is not working too. This is a better solution which Peter suggested: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values – bman Aug 06 '11 at 06:38
  • Why is there a `return this.each(function() `? – powtac Sep 03 '11 at 21:08
  • 2
    @powtac - so you can call .ForceNumericOnly() on multiple objects. For example... $("input[type='text']").ForceNumericOnly() – Oliver Pearmain Sep 29 '11 at 10:06
  • 1
    @powtac the `each` from `return this.each(function()` is to allow multiple objects as HaggleLad said, and the `return` part is to return the jQuery object back to the caller, to allow chaining such as `$("input[type='text'").ForceNumericOnly().show()` – Jose Rui Santos Dec 01 '11 at 12:04
  • Beautifull but please add `key == 13 ||` to make sure Enter is allowed, for form submital and such – Pawel Cioch Mar 27 '14 at 23:12
  • 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 mozilla – Jatinder Sharma Feb 16 '15 at 07:55
  • Thnx. Its possible to control only one decimal point? – JTCon May 22 '21 at 15:06
  • and a max value? – JTCon May 22 '21 at 15:23
  • Thx, but it allows some characters like á, é – Jurakin Jul 01 '22 at 18:15
179

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">
Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Patrick Fisher
  • 7,926
  • 5
  • 35
  • 28
  • 2
    This moves the caret to the end even if the user is pressing left arrow key. – Phrogz Jan 19 '12 at 00:33
  • 1
    @phrogz, try this: `onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"`. – Patrick Fisher Mar 01 '12 at 19:12
  • This works perfectly, and prevents Shift+number unlike those above. – Nick Hartley Mar 12 '12 at 10:54
  • Almost perfect - leading minus signs are lost. It's beyond me though how to preserve one if it is there. – Neil Moss Mar 21 '12 at 13:54
  • 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 || ''; }"`. – Patrick Fisher Apr 02 '12 at 00:01
  • I find the inline method to be the cleanest. Thanks! – DigiOz Multimedia Jun 06 '12 at 16:35
  • 1
    At least on Chrome 24, this causes the non-number to appear and then it is immediately deleted, which looks pretty cheesy (compared to preventing the non-number from being entered in the first place). – mhenry1384 Jan 21 '13 at 16:01
  • 6
    @mhenry1384 That is expected behavior. I find it to be nice feedback but if you don't like that, then a key code approach would be what you're looking for. – Patrick Fisher Jan 24 '13 at 06:54
  • 2
    You could modify to `/[^0-9]|^0+(?!$)/g` to prevent leading series of zero. – Johny Skovdal Feb 18 '13 at 20:44
  • Can this be modified to allow a decimal / full stop? – James Wilson Nov 18 '13 at 15:50
  • 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; }"`. – Patrick Fisher Dec 09 '13 at 22:09
  • best answer as it permits every kind of keyboard – kheraud May 25 '15 at 11:48
  • hi, how can I ensure numeric value with a `decimal` between `0.0` to `24.0` I am unable to let it enter the `.` – Transformer Apr 02 '17 at 00:29
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();
    }
Aaron Butacov
  • 32,415
  • 8
  • 47
  • 61
TheDeveloper
  • 151
  • 1
  • 2
  • 2
107

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

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, '');
  });
WizLiz
  • 2,068
  • 5
  • 25
  • 39
Rid Iculous
  • 3,696
  • 3
  • 23
  • 28
  • 7
    I'd replace keyup by input, otherwise you can maintain a letter pressed then click to take the focus out of the textbox and it leave the text as is. input assure that this can't happen – WizLiz Aug 04 '16 at 14:34
  • 3
    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, ''); }); – BradM Jan 17 '17 at 03:03
  • 6
    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. – Paul May 03 '17 at 01:27
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

Amr Elgarhy
  • 66,568
  • 69
  • 184
  • 301
  • 41
    Well... "Not using JQuery" except for the part of your example that is using JQuery... – GalacticCowboy Apr 28 '10 at 16:05
  • `document.getElementById('inputid').val()` dude.. that's still jquery. `.val()` is a jquery thing. use `.value` – mpen Mar 18 '11 at 06:09
  • 12
    [Using `isNaN` alone is a bad idea because of JavaScript type coercion.](http://stackoverflow.com/questions/5663141/simple-number-validation-javascript-jquery/5663507#5663507) – josh3736 Apr 14 '11 at 13:51
  • hi, how can I ensure numeric value with a `decimal` between `0.0` to `24.0` I am unable to let it enter the `.` – Transformer Apr 02 '17 at 00:31
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

Ivar
  • 4,344
  • 6
  • 38
  • 53
  • 7
    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 Jun 15 '09 at 10:00
  • @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. – Ivar Jun 15 '09 at 10:10
  • 4
    Try pressing Shift + 8 for instance - your validation will let * get in – Anton Aug 20 '10 at 11:59
  • This is nice.Would be much better,If it handles the Shift key+Numbers (Special chars like !@#$%^..) – Shyju Oct 29 '10 at 19:37
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;
});
Mike
  • 21
  • 2
  • 3
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.

guest
  • 2,185
  • 3
  • 23
  • 46
  • 2
    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. – Markus Jan 16 '15 at 15:26
  • it looks like it's well supported by most browsers by now, so modernizr support isn't so important: http://caniuse.com/#search=pattern Safari works very well even though it's listed as partially supported on this site. Try it! – guest Jul 24 '15 at 23:48
  • @guest Thank you so much for this. Quickest and easiest answer! Top answer in my opinion. – BinaryJoe01 Aug 29 '17 at 22:51
26

Simpler one for me is

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});
IT ppl
  • 2,626
  • 1
  • 39
  • 56
Summved Jain
  • 872
  • 2
  • 18
  • 21
  • 8
    Just need to be sure you use `this.value.replace(/[^0-9\.]/g,'');` to include OP's requirements of 0-9 – Chalise Jan 02 '13 at 16:42
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!!!

Al Foиce ѫ
  • 4,195
  • 12
  • 39
  • 49
Ganesh Babu
  • 3,590
  • 11
  • 34
  • 67
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.

vickisys
  • 2,008
  • 2
  • 20
  • 27
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.

Vitalii Fedorenko
  • 110,878
  • 29
  • 149
  • 111
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)');
shasi kanth
  • 6,987
  • 24
  • 106
  • 158
Adrian
  • 353
  • 2
  • 7
  • 20
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">
10
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
        }
    }
Pathik Vejani
  • 4,263
  • 8
  • 57
  • 98
user261922
  • 31
  • 1
  • 2
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">
Gobinda Nandi
  • 457
  • 7
  • 18
V J I
  • 79
  • 3
  • 7
10

If have a smooth OneLiner:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >
  • Great solution but is onkeypress not depreciated? Replacing this with onkeydown actually causes a problem, it does not allow a backspace? – code-is-life May 01 '22 at 15:23
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
Vincent
  • 938
  • 13
  • 20
  • Hey i am using this but what i am really looking is to allow him dot like 1.2 or 3.455 like that – Vivekh Dec 27 '13 at 08:55
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()"/>
Community
  • 1
  • 1
karim79
  • 339,989
  • 67
  • 413
  • 406
  • 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 . – Kiran Ruth R Jun 24 '13 at 11:43
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 ;
  })
Asif
  • 258
  • 1
  • 6
  • 19
  • 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;` – tomvo Jun 06 '13 at 15:06
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);
});
Flexo
  • 87,323
  • 22
  • 191
  • 272
Dima
  • 1,045
  • 14
  • 23
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;
    }
});
Reactgular
  • 52,335
  • 19
  • 158
  • 208
  • does this ensure $ and then + - as first or first/second characters and then only 1 decimal point? – gordon Aug 23 '16 at 17:59
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));
});
Jonathan
  • 8,771
  • 4
  • 41
  • 78
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();
    }
});
SoN9ne
  • 319
  • 4
  • 5
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;
        }
    });
});
jamesbar2
  • 614
  • 1
  • 9
  • 20
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(); 
        }   
    }
});
Ofir Farchy
  • 7,657
  • 7
  • 38
  • 58
ngwanevic
  • 13
  • 1
  • 2
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();
                }
            }
Coppermill
  • 6,676
  • 14
  • 67
  • 92
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;
    }
Pragnesh Rupapara
  • 782
  • 1
  • 12
  • 30
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

Jitender Kumar
  • 2,439
  • 4
  • 29
  • 43
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

kkk
  • 1,850
  • 1
  • 25
  • 45
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 ;)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
crash
  • 9
  • 1
  • 1
5

You can use the following code.

<input type="text" onkeypress="return event.charCode &gt;= 48 &amp;&amp; event.charCode &lt;= 57">
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...

Pedro Soares
  • 623
  • 2
  • 10
  • 15
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();
    }
});  
Novasol
  • 887
  • 10
  • 17
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.]+");
jBelanger
  • 1,526
  • 18
  • 11
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

Tom Van Schoor
  • 269
  • 2
  • 5
  • 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,'')"`. – Patrick Fisher Jun 05 '11 at 03:48
  • 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... – Tom Van Schoor Jun 20 '11 at 05:59
  • @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(); });` – Gruber Jun 05 '12 at 07:40
  • @Gruber 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. – Patrick Fisher Jun 12 '12 at 03:29
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();
                    }
                }
            }
        );
Damiano Fusco
  • 215
  • 3
  • 6
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.

Asterios Raptis
  • 440
  • 1
  • 3
  • 11
  • 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) ) – Deise Vicentin May 25 '16 at 14:09
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)

mencargo
  • 111
  • 4
  • 11
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
        }
    }
});
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
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.

balrok
  • 444
  • 3
  • 8
2

add below code in document.ready

    $('.class of text box').keyup(function () 
    {
    this.value = this.value.replace(/[^0-9]/g, '');
    });  
rinuthomaz
  • 1,393
  • 2
  • 23
  • 38
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/

Community
  • 1
  • 1
Gagan Gami
  • 10,121
  • 1
  • 29
  • 55
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.

vibs2006
  • 6,028
  • 3
  • 40
  • 40
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/

Ryan Charmley
  • 1,127
  • 15
  • 18
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.

dhinesh
  • 4,676
  • 2
  • 26
  • 44
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);
});
Hooman Limouee
  • 1,143
  • 2
  • 21
  • 43
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)
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!)

Community
  • 1
  • 1
Tohid
  • 6,175
  • 7
  • 51
  • 80
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;
    }
});
LCJ
  • 22,196
  • 67
  • 260
  • 418
0

Check if decimal point already used:-

        // Stop: Multiple decimal points
        if((e.keyCode == 190 || e.keyCode == 110) && ((this.value).indexOf(".") >= 0))
            e.preventDefault(); 
buzzmonkey
  • 187
  • 1
  • 1
  • 5
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
}
Khaled.K
  • 5,828
  • 1
  • 33
  • 51
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();
        }
    }
}
branchgabriel
  • 4,241
  • 4
  • 34
  • 48
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, ''));    

});
Mrinal Jha
  • 11
  • 2
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.

Valera Tumash
  • 628
  • 7
  • 16
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();
        }
    });
}
Ganga Reddy
  • 11
  • 1
  • 5
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 :-)

Ali Raza
  • 183
  • 14
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">
Ouatataz
  • 185
  • 3
  • 12
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">
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);
});
aefxx
  • 24,835
  • 6
  • 45
  • 55
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;
});
Balamurugan M
  • 580
  • 5
  • 9
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">
mrid
  • 5,782
  • 5
  • 28
  • 71
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.

Adriaan Tijsseling
  • 2,025
  • 1
  • 18
  • 23
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(); 
        }   
    }
});
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
-1

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

shane lee
  • 1,290
  • 15
  • 17
-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.

eeerahul
  • 1,629
  • 4
  • 27
  • 38