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

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


当前回答

您可以使用以下代码。

<input type=“text” onkeypress=“return event.charCode >= 48 && event.charCode <= 57”>

其他回答

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

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

有一个难以置信的兼容性问题,使用按键来检测被按下的字符…参见quirksmode了解更多信息。

我建议使用keyup来创建过滤器,因为这样就可以使用$(element).val()方法来计算实际的通用字符。

然后你可以过滤掉任何非数字使用正则表达式,如:

替换(/ [^ 0 - 9]/ g,”);

这就解决了所有的问题,比如移动和粘贴问题,因为总是有一个键up,所以值总是会被求值(除非javascript被关闭)。

所以…把它变成JQuery…这是我正在写的一个未完成的插件,它叫做inputmask,完成后将支持更多的掩码。现在它有数字掩码工作。

开始了……

/**
 * @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);

要使用它,只需这样做:

$('#someElementId').inputmask({
  validators: ['digits','someOtherNotYetImplementedValidator']
});

'someOtherNotYetImplementedValidator'只是在那里展示如何扩展它以用于额外的未来掩码/验证器。你可以添加或删除它,它不会破坏任何东西;-)

为这些额外杂乱的评论道歉,我使用的是我为这里的工作人员创建的模板。

希望这能有所帮助, 干杯

很多人在这里使用键码属性,这是不容易记住的。如果你没有语言环境问题,那么你可以简单地使用键,这实际上是用户键入的输入。

看这把小提琴

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

然后查看下面的简单代码。

请注意,此示例还包含对十进制输入的验证。

对于这个问题,它不是必需的,所以您可以简单地删除大小写“。”以删除小数的条目。

需要确保你有数字键盘和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();
                }
            }

没有一个答案在我的情况下工作,所以我在接受的答案做了一点改变,使它为动态添加的元素工作。

享受:

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

用法:

inputFilter('#onlyDigitsInput', function (val) {
    return /^\d*$/.test(val);
});