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

发布于 2024-07-25 00:57:12 字数 100 浏览 9 评论 0原文

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

我怎样才能使用 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

高冷爸爸 2024-08-01 00:57:12

注意:这是更新的答案。 下面的评论引用了一个与键码混淆的旧版本。

jQuery

自己尝试一下在 JSFiddle 上。

没有本机 jQuery 实现,但您可以使用以下 inputFilter 过滤文本 的输入值code> 插件(支持复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可输入的键、插入符号位置、不同的键盘布局、有效性错误消息和 自 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));

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

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

将您喜欢的样式应用到输入错误类别。 这里有一个建议:

.input-error{
  outline: 1px solid red;
}

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

纯 JavaScript(不含 jQuery)

实际上并不需要 jQuery,您也可以使用纯 JavaScript 执行相同的操作。 请参阅此答案

HTML 5

HTML 5 有一个带有 的本机解决方案(请参阅 规范),但请注意,浏览器支持各不相同:

  • 大多数浏览器仅在提交表单时验证输入,而不是在键入时验证输入。
  • 大多数移动浏览器不支持步骤minmax 属性。
  • Chrome(版本 71.0.3578.98)仍然允许用户在字段中输入字符 eE。 另请参阅此问题
  • Firefox(版本 64.0)和 Edge(EdgeHTML 版本 17.17134)仍然允许用户在字段中输入任何文本。

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

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.

圈圈圆圆圈圈 2024-08-01 00:57:12

这是我使用的函数:

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

然后您可以通过执行以下操作将其附加到您的控件:

$("#yourTextBoxName").ForceNumericOnly();

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();
带上头具痛哭 2024-08-01 00:57:12

排队:

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

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

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

冷心人i 2024-08-01 00:57:12

您可以像这样在输入事件上使用:

$(document).on("input", ".numeric", function() {
    this.value = this.value.replace(/\D/g,'');
});

但是,这个代码特权是什么?

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

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.
紫罗兰の梦幻 2024-08-01 00:57:12

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

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

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

或者对于事件键码,简单使用如下:

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

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();
    }
天暗了我发光 2024-08-01 00:57:12

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

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

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, '');
  });
场罚期间 2024-08-01 00:57:12

使用 JavaScript 函数 isNaN,

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

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

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

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

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

难以启齿的温柔 2024-08-01 00:57:12
$(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(); 
            }   
        }
    });
});

来源:http://snipt.net/GerryEng/jquery-making -文本字段仅接受数字值

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

变身佩奇 2024-08-01 00:57:12

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

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

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;
});
土豪我们做朋友吧 2024-08-01 00:57:12

对我来说更简单的是

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

Simpler one for me is

jQuery('.plan_eff').keyup(function () {     
  this.value = this.value.replace(/[^1-9\.]/g,'');
});
非要怀念 2024-08-01 00:57:12

为什么这么复杂? 您甚至不需要 jQuery,因为有一个 HTML5 模式属性:

<input type="text" pattern="[0-9]*">

最酷的事情是它在移动设备上显示数字键盘,这比使用 jQuery 好得多。

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.

面犯桃花 2024-08-01 00:57:12

您可以使用这个非常简单的解决方案执行相同的操作

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

我参考了此链接解决方案。 它工作完美!

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

红衣飘飘貌似仙 2024-08-01 00:57:12

您可以尝试 HTML5 number 输入:

<input type="number" value="0" min="0"> 

对于不兼容的浏览器,有ModernizrWebforms2 后备。

You can try the HTML5 number input:

<input type="number" value="0" min="0"> 

For non-compliant browsers there are Modernizr and Webforms2 fallbacks.

茶花眉 2024-08-01 00:57:12

HTML5 中的pattern 属性指定一个正则表达式,用于检查元素的值。

  <input  type="text" pattern="[0-9]{1,3}" value="" />

注意:pattern 属性适用于以下输入类型:文本、搜索、url、电话、电子邮件和密码。

  • [0-9]可以替换为任意正则表达式条件。

  • {1,3} 表示最少可以输入1位,最多可以输入3位数字。

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.

遗忘曾经 2024-08-01 00:57:12
function suppressNonNumericInput(event){
        if( !(event.keyCode == 8                                // backspace
            || event.keyCode == 46                              // delete
            || (event.keyCode >= 35 && event.keyCode <= 40)     // arrow keys/home/end
            || (event.keyCode >= 48 && event.keyCode <= 57)     // numbers on keyboard
            || (event.keyCode >= 96 && event.keyCode <= 105))   // number on keypad
            ) {
                event.preventDefault();     // Prevent character input
        }
    }
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
        }
    }
懒猫 2024-08-01 00:57:12

使用 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)');

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)');
眼泪都笑了 2024-08-01 00:57:12

这里有两种不同的方法:

  1. 允许带小数点的数值
  2. 允许不带小数点的数值

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

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

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

就是爱搞怪 2024-08-01 00:57:12

如果有一个平滑的 OneLiner:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >

If have a smooth OneLiner:

<input type="text" onkeypress="return /[0-9]/i.test(event.key)" >
云胡 2024-08-01 00:57:12

在 html 代码中尝试一下,就像 onkeypress 和 onpast

<input type="text" onkeypress="return event.charCode >= 48 && event.charCode <= 57" onpaste="return false">

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">
橘虞初梦 2024-08-01 00:57:12

我找到了一个非常好的且简单的解决方案,它不会像其他解决方案那样阻止用户选择文本或复制粘贴。 jQuery 风格:)

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

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
舞袖。长 2024-08-01 00:57:12

你可以使用这个 JavaScript 函数:

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

你可以将它绑定到你的文本框,如下所示:

$(document).ready(function() {
    $('#myTextbox').keydown(maskInput);
});

我在生产中使用了上面的函数,它工作得很好,而且是跨浏览器的。 此外,它不依赖于 jQuery,因此您可以使用内联 JavaScript 将其绑定到文本框:

<input type="text" name="aNumberField" onkeydown="javascript:maskInput()"/>

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()"/>
秋凉 2024-08-01 00:57:12

我想这会对大家有帮助

  $('input.valid-number').bind('keypress', function(e) { 
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)) ? false : true ;
  })

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 ;
  })
第七度阳光i 2024-08-01 00:57:12

这是我前段时间创建的一个快速解决方案。 您可以在我的文章中阅读更多相关信息:

http://ajax911.com/numbers-numeric-field-jquery/< /a>

$("#textfield").bind("keyup paste", function(){
    setTimeout(jQuery.proxy(function() {
        this.val(this.val().replace(/[^0-9]/g, ''));
    }, $(this)), 0);
});

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);
});
以为你会在 2024-08-01 00:57:12

这就是我最近写信来实现这一目标的原因。 我知道这个问题已经得到解答,但我将其留待以后使用。

该方法只允许0-9键盘和小键盘、退格键、制表符、左右箭头(普通形式操作)

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

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();
    }
});
终弃我 2024-08-01 00:57:12

我根据上面 @user261922 的帖子编写了我的文章,稍作修改,以便您可以选择全部、选项卡,并且可以处理同一页面上的多个“仅数字”字段。

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

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;
        }
    });
});
开始看清了 2024-08-01 00:57:12

我也想回答:)

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

就是这样......只是数字。 :) 几乎它可以只与“模糊”一起工作,但是......

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

千仐 2024-08-01 00:57:12

您希望允许选项卡:

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

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(); 
        }   
    }
});
梦情居士 2024-08-01 00:57:12

这是使用 jQuery UI Widget 工厂的答案。 您可以轻松自定义允许使用的字符。

$('input').numberOnly({
    valid: "0123456789+-.$,"
});

这将允许数字、数字符号和美元金额。

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

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;
    }
});
烟酉 2024-08-01 00:57:12

这看起来是牢不可破的。

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

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));
});
内心激荡 2024-08-01 00:57:12

需要确保数字键盘和 Tab 键也能正常工作

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

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();
                }
            }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文