Best way to restrict a text field to numbers only?

前端 未结 29 1695
长情又很酷
长情又很酷 2020-12-04 22:01

I\'m using the following Javascript to restrict a text field on my website to only accept numerical input, and no other letters or characters. The problem is, it REALLY reje

29条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 22:17

    This is my plugin for that case:

     (function( $ ) {
        $.fn.numbers = function(options) {
          $(this).keypress(function(evt){
              var setting = $.extend( {
                    'digits' : 8
                  }, options);
              if($(this).val().length > (setting.digits - 1) && evt.which != 8){
                  evt.preventDefault(); 
              }
              else{
                  if(evt.which < 48 || evt.which > 57){
                    if(evt.keyCode != 8){
                        evt.preventDefault();  
                    }
                  }
              }
          });
        };
      })( jQuery );
    

    Use:

     $('#limin').numbers({digits:3});
     $('#limax').numbers();
    

提交回复
热议问题