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

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


当前回答

下面是另一种方法。这也可以用于粘贴。[用于字母-数字验证]

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

其他回答

您可以使用这个非常简单的解决方案来实现同样的目的

$(“input.numbers”).keypress(function(event) { 返回 /\d/.test(String.fromCharCode(event.keyCode)); }); <script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js”></script> <输入类型=“文本” 类=“数字” 名称=“field_name” />

我参考了这个链接来获得解决方案。它工作得很完美!!

注:这是更新后的答案。下面的注释指的是一个老版本,混乱的关键代码。

jQuery

自己在JSFiddle上试试。

没有原生的jQuery实现,但你可以过滤文本<input>的输入值,使用以下inputFilter插件(支持复制+粘贴,拖放,键盘快捷键,上下文菜单操作,不可键入的键,插入符号位置,不同的键盘布局,有效性错误消息,以及ie9以来的所有浏览器):

// 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有一个本地的解决方案<input type="number">(参见规范),但请注意浏览器的支持不同:

大多数浏览器只在提交表单时验证输入,而在输入时不验证。 大多数移动浏览器不支持step、min和max属性。 Chrome(版本71.0.3578.98)仍然允许用户在字段中输入字符e和e。还有这个问题。 Firefox(版本64.0)和Edge (EdgeHTML版本17.17134)仍然允许用户在字段中输入任何文本。

自己去w3schools.com试试吧。

这似乎牢不可破。

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

如果有一个平滑的onlineer:

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

下面是一个使用jQuery UI小部件工厂的答案。您可以轻松地自定义允许的字符。

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