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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/995183/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:21:39  来源:igfitidea点击:

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

jqueryhtmlvalidationnumeric

提问by Prashant

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.

我正在创建一个网页,其中有一个输入文本字段,我只想在其中允许数字字符,例如 (0,1,2,3,4,5...9) 0-9。

How can I do this using jQuery?

我如何使用 jQuery 做到这一点?

回答by kgiannakakis

Note:This is an updated answer. Comments below refer to an old version which messed around with keycodes.

注意:这是一个更新的答案。下面的评论指的是一个旧版本,它弄乱了键码。

jQuery

jQuery

Try it yourself on JSFiddle.

在 JSFiddle 上自己尝试一下。

There is no native jQuery implementation for this, but you can filter the input values of a text <input>with the following inputFilterplugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, and all browsers since IE 9):

没有针对此的原生 jQuery 实现,但您可以<input>使用以下inputFilter插件过滤文本的输入值(支持复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可键入的键、插入符号位置、不同的键盘布局,以及自 IE 9 以来的所有浏览器):

// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
      if (inputFilter(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);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

You can now use the inputFilterplugin to install an input filter:

您现在可以使用该inputFilter插件安装输入过滤器:

$(document).ready(function() {
  $("#myTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

See the JSFiddle demofor more input filter examples. Also note that you still must do server side validation!

有关更多输入过滤器示例,请参阅JSFiddle 演示。另请注意,您仍然必须进行服务器端验证!

Pure JavaScript (without jQuery)

纯 JavaScript(没有 jQuery)

jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See this answer.

实际上并不需要 jQuery,你也可以用纯 JavaScript 做同样的事情。看到这个答案

HTML 5

HTML 5

HTML 5 has a native solution with <input type="number">(see the specification), but note that browser support varies:

HTML 5 有一个本机解决方案<input type="number">(请参阅规范),但请注意浏览器支持各不相同:

  • Most browsers will only validate the input when submitting the form, and not when typing.
  • Most mobile browsersdon't support the step, minand maxattributes.
  • Chrome (version 71.0.3578.98) still allows the user to enter the characters eand Einto the field. Also see this question.
  • Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter anytext into the field.
  • 大多数浏览器只会在提交表单时验证输入,而不是在输入时验证。
  • 大多数移动浏览器不支持step,minmax属性。
  • Chrome(版本 71.0.3578.98)仍然允许用户输入字符eE进入字段。另请参阅此问题
  • Firefox(版本 64.0)和 Edge(EdgeHTML 版本 17.17134)仍然允许用户在字段中输入任何文本。

Try it yourself on w3schools.com.

在 w3schools.com 上亲自尝试一下。

回答by Kelsey

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

回答by Patrick Fisher

Inline:

排队:

<input name="number" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')">

Unobtrusive style (with jQuery):

不显眼的风格(使用 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">

回答by TheDeveloper

You could just use a simple JavaScript regular expression to test for purely numeric characters:

您可以使用简单的 JavaScript 正则表达式来测试纯数字字符:

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

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

如果输入是数字,则返回 true,否则返回 false。

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

回答by Hamid Afarinesh Far

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.
  • 它适用于移动浏览器(keydown 和 keyCode 有问题)。
  • 它也适用于 AJAX 生成的内容,因为我们使用的是“on”。
  • 比 keydown 更好的性能,例如在粘贴事件上。

回答by Rid Iculous

Short and sweet - even if this will never find much attention after 30+ answers ;)

简短而甜蜜 - 即使这在 30 多个答案之后永远不会引起太多关注;)

  $('#number_only').bind('keyup paste', function(){
        this.value = this.value.replace(/[^0-9]/g, '');
  });

回答by Amr Elgarhy

Use JavaScript function isNaN,

使用 JavaScript 函数isNaN

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

if (isNaN(document.getElementById('inputid').val()))

如果 (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

更新:这里有一篇很好的文章谈论它,但使用 jQuery:将HTML 文本框中的输入限制为数值

回答by Ivar

$(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

来源:http: //snipt.net/GerryEng/jquery-making-textfield-only-accept-numeric-values

回答by Mijk

I use this in our internal common js file. I just add the class to any input that needs this behavior.

我在我们内部通用的 js 文件中使用了它。我只是将该类添加到需要此行为的任何输入中。

$(".numericOnly").keypress(function (e) {
    if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});

回答by Summved Jain

Simpler one for me is

对我来说更简单的是

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});