如何只允许数字(0-9)在 HTML 输入框使用 jQuery?

I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.

How can I do this using jQuery?

转载于:https://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery

csdnceshi75
衫裤跑路 That doesn't actually restrict what you type in just the numbers you can click up and down to.
2 年多之前 回复
csdnceshi59
ℙℕℤℝ I've down voted this question because you're asking us to write code for you. What have you actually tried?
大约 4 年之前 回复
csdnceshi63
elliott.david lastest version of chrome though I've had the same issue with MS Edge, no pasting involved. Just regular input on the keyboard.
大约 4 年之前 回复
weixin_41568174
from.. Which browser[+version]/os? Did you enter the char or did you use ctrl+v?
大约 4 年之前 回复
csdnceshi63
elliott.david 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.
大约 4 年之前 回复
weixin_41568174
from.. can you explain what exactly doesn't work for you?
大约 4 年之前 回复
csdnceshi54
hurriedly% - Javascript being on/off is irrelevant. You must always validate on the server.
接近 5 年之前 回复
weixin_41568110
七度&光 possible duplicate of jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)
接近 6 年之前 回复
csdnceshi66
必承其重 | 欲带皇冠 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" />
6 年多之前 回复
csdnceshi79
python小菜 Doesn't work in any current versions of IE. It's all well and good to use the latest code on your own stuff to keep fresh, but this isn't really an option for almost any professional project. caniuse.com/#feat=input-number
7 年多之前 回复
csdnceshi72
谁还没个明天 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.
接近 8 年之前 回复
csdnceshi67
bug^君 Refer my answer stackoverflow.com/questions/995183/…
大约 8 年之前 回复
weixin_41568126
乱世@小熊 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.
8 年多之前 回复
weixin_41568183
零零乙 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.
8 年多之前 回复
csdnceshi64
游.程 have you considered html5? <input type="number" />. with min and max attributes you can restrict input too
8 年多之前 回复
csdnceshi70
笑故挽风 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.
11 年多之前 回复

28个回答

Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.

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

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            (e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) || 
             // Allow: home, end, left, right, down, up
            (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();
        }
    });
});

NOTE: If your webpage uses HTML5, you can use the built in <input type="number"> and use the min and max properties to control the minimum and maximum value.


The following is minimized and also allows for use of CTRL+X, CTRL+C, and CTRL+V

$(function() {
  $('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
    <input id="child" type="textarea" />
</div>

</div>
csdnceshi73
喵-见缝插针 Not every hero wears a cape hahaha, thanks a lot guy!
2 年多之前 回复
csdnceshi53
Lotus@ however we can still copy text from any text source and paste it in textbox
3 年多之前 回复
csdnceshi52
妄徒之命 This for protected multiple dot if (e.keyCode == 190 && $(this).val().indexOf(".") > -1) { return false; }
接近 4 年之前 回复
csdnceshi54
hurriedly% Don't take it. It doesn't prevent key combination, like alt + number, spanish accent key... Better answer: http://stackoverflow.com/a/7295864/3710490.Here is screenshot of error: http://img10.lostpic.net/2016/06/12/8dd58e87f2310edb79c25d8571fb6261.png
4 年多之前 回复
csdnceshi79
python小菜 What about this number: 0...............0. It is till allow in the input field
4 年多之前 回复
csdnceshi70
笑故挽风 Miss the keyboard pad at the right.
4 年多之前 回复
weixin_41568131
10.24 if ctrl+v a invalid char, the script do not detect.
大约 5 年之前 回复
csdnceshi68
local-host 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 extras
5 年多之前 回复
weixin_41568183
零零乙 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?
5 年多之前 回复
csdnceshi61
derek5. add event.keyCode == 40 for Up button
接近 6 年之前 回复
weixin_41568174
from.. 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; }
大约 6 年之前 回复
csdnceshi57
perhaps? With thanks to all, I wrote another with min and max range. You could see in: stackoverflow.com/questions/2013229/… @miniQuark please tell me if you have any point.
大约 6 年之前 回复
weixin_41568208
北城已荒凉 How can i avoid 0 value i want 1 to 9, 10 is acceptable but single 0 should not be there.
6 年多之前 回复
csdnceshi65
larry*wei Add this // Allow: . dot for decimals (event.keyCode == 110 || event.keyCode == 190)
大约 7 年之前 回复
csdnceshi63
elliott.david How does the edit must made a moment ago address the problem? I'm not convinced it's a valid edit.
大约 7 年之前 回复
weixin_41568127
?yb? 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.. :-)
7 年多之前 回复
csdnceshi76
斗士狗 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.
接近 8 年之前 回复
csdnceshi80
胖鸭 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 ))
接近 8 年之前 回复
csdnceshi55
~Onlooker Don't we need to allow Backspace and Delete keys?
大约 8 年之前 回复
csdnceshi72
谁还没个明天 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...
8 年多之前 回复
csdnceshi50
三生石@ You may also want to allow for function keys like F5 for example to refresh the page
8 年多之前 回复
csdnceshi58
Didn"t forge Also add event.keyCode==110 to allow decimals from the numeric keypad.
8 年多之前 回复
weixin_41568184
叼花硬汉 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.
8 年多之前 回复
csdnceshi75
衫裤跑路 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 !@#$%^&*()
8 年多之前 回复
csdnceshi75
衫裤跑路 added tab, escape, ctrl+a, end, home, left, right
8 年多之前 回复
weixin_41568184
叼花硬汉 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)
8 年多之前 回复
csdnceshi69
YaoRaoLov Thanks! event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 if you want decimals
大约 9 年之前 回复
csdnceshi64
游.程 texotela.co.uk/code/jquery/numeric this one works for me :) thanks
11 年多之前 回复

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();
csdnceshi63
elliott.david really simple :)
大约 4 年之前 回复
csdnceshi64
游.程 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
5 年多之前 回复
csdnceshi67
bug^君 Beautifull but please add key == 13 || to make sure Enter is allowed, for form submital and such
6 年多之前 回复
csdnceshi58
Didn"t forge crazy stuff. Very good idea!
接近 9 年之前 回复
csdnceshi50
三生石@ 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()
接近 9 年之前 回复
csdnceshi80
胖鸭 - so you can call .ForceNumericOnly() on multiple objects. For example... $("input[type='text']").ForceNumericOnly()
接近 9 年之前 回复
csdnceshi58
Didn"t forge Why is there a return this.each(function() ?
大约 9 年之前 回复
csdnceshi77
狐狸.fox Keys "Home", "End" is not working too. This is a better solution which Peter suggested: west-wind.com/weblog/posts/2011/Apr/22/…
大约 9 年之前 回复
weixin_41568131
10.24 This script does not work for Shift + 2 or 3
9 年多之前 回复
csdnceshi78
程序go 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?
大约 10 年之前 回复

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

</div>
csdnceshi51
旧行李 hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
3 年多之前 回复
weixin_41568184
叼花硬汉 best answer as it permits every kind of keyboard
5 年多之前 回复
csdnceshi62
csdnceshi62 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; }".
接近 7 年之前 回复
weixin_41568127
?yb? Can this be modified to allow a decimal / full stop?
接近 7 年之前 回复
csdnceshi67
bug^君 You could modify to /[^0-9]|^0+(?!$)/g to prevent leading series of zero.
7 年多之前 回复
csdnceshi62
csdnceshi62 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.
7 年多之前 回复
csdnceshi69
YaoRaoLov 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).
7 年多之前 回复
weixin_41568196
撒拉嘿哟木头 I find the inline method to be the cleanest. Thanks!
8 年多之前 回复
csdnceshi62
csdnceshi62 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 || ''; }".
8 年多之前 回复
csdnceshi56
lrony* Almost perfect - leading minus signs are lost. It's beyond me though how to preserve one if it is there.
8 年多之前 回复
csdnceshi65
larry*wei This works perfectly, and prevents Shift+number unlike those above.
8 年多之前 回复
csdnceshi62
csdnceshi62 try this: onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')".
8 年多之前 回复
csdnceshi59
ℙℕℤℝ Works like a charm.
8 年多之前 回复
csdnceshi61
derek5. This moves the caret to the end even if the user is pressing left arrow key.
8 年多之前 回复

Simpler one for me is

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});
csdnceshi69
YaoRaoLov worked for me thanks
大约 4 年之前 回复
csdnceshi53
Lotus@ Just need to be sure you use this.value.replace(/[^0-9\.]/g,''); to include OP's requirements of 0-9
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 ;
  })
csdnceshi56
lrony* 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;
7 年多之前 回复

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

weixin_41568208
北城已荒凉 Yeah but it works fine with modern browsers
接近 5 年之前 回复
weixin_41568126
乱世@小熊 it will not work for old browsers
接近 5 年之前 回复

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

</div>
csdnceshi80
胖鸭 hi, how can I ensure numeric value with a decimal between 0.0 to 24.0 I am unable to let it enter the .
3 年多之前 回复
csdnceshi75
衫裤跑路 This works perfect in crome. But not in Mozilla FireFox
4 年多之前 回复
weixin_41568196
撒拉嘿哟木头 Maybe this is better /\d|\./ to allow . decimal numbers
接近 6 年之前 回复

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

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;
});
csdnceshi67
bug^君 Nice, elegant and useful code! Thanks. But you must add keyup and keydown events.
大约 7 年之前 回复

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()"/>
csdnceshi58
Didn"t forge 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 .
7 年多之前 回复
共28条数据 1 3 尾页
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐