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

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


当前回答

$(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-textfield-only-accept-numeric-values

其他回答

对我来说更简单的是

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

有一个难以置信的兼容性问题,使用按键来检测被按下的字符…参见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'只是在那里展示如何扩展它以用于额外的未来掩码/验证器。你可以添加或删除它,它不会破坏任何东西;-)

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

希望这能有所帮助, 干杯

function validate_profile(frmid) {
    var form = $('#' + frmid);
    var error = $('.alert-danger', form);
    var success = $('.alert-success', form);
    form.validate({
        errorElement: 'span', //default input error message container
        errorClass: 'help-block', // default input error message class
        focusInvalid: true, // do not focus the last invalid input
        ignore: "",
        rules: {
            contact_no: {
                required: true,
                minlength: 10,
                maxlength: 10,
                number: true
            }, email_id: {
                required: true,
                email: true
            }
        },
        invalidHandler: function (event, validator) { //display error alert on form submit   
            success.hide();
            error.show();
            Metronic.scrollTo(error, -7000);
        },
        highlight: function (element) { // hightlight error inputs
            $(element)
                    .closest('.form-group').addClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').removeClass('has-success'); // set success class to the control group
        },
        unhighlight: function (element) { // revert the change done by hightlight
            $(element)
                    .closest('.form-group').removeClass('has-error'); // un set error class to the control group
            $(element)
                    .closest('.form-group').addClass('has-success'); // set success class to the control group
            error.hide();
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error');
            label.closest('.form-group').addClass('has-success');
        },
        submitHandler: function (form) {
            success.show();
            error.hide();
            form.submit();
        }
    });
}

我对上面的答案有问题。它不包括数字键盘,如果一个按shift+数字的特殊符号也不应该显示。但是这个解没有考虑到它。

我在这篇文章中找到的最好的链接是: http://www.west-wind.com/weblog/posts/2011/Apr/22/Restricting-Input-in-HTML-Textboxes-to-Numeric-Values

我是stackoverflow的新手,所以我不知道我是否可以把更好的解决方案编辑到顶层。

function Numbers(e)
{
    if($.browser.msie)
    {
        if(e.keyCode > 47 && e.keyCode < 58)
            return true;
        else
            return false;
    }
    else
    {
        if((e.charCode > 47 && e.charCode < 58) || (e.charCode == 0))
            return true;
        else
            return false;
    }
}

我希望这在所有浏览器上都能工作。