开发者

Disable user of 0 as first number in input box jquery

I have an input box:

<input class="longboxsmall" type="text" name="number" value=""/>

And I want to disallow the number 0 being the first number entered in the box how can I do thi开发者_StackOverflow中文版s??? Can I use Jquery??


$(".longboxsmall").keyup(function(){
    var value = $(this).val();
    value = value.replace(/^(0*)/,"");
    $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="longboxsmall" type="text" name="number" value=""/>

JS

$(".longboxsmall").keyup(function(){
    var value = $(this).val();
    value = value.replace(/^(0*)/,"");
    $(this).val(value);
});

HTML

<input class="longboxsmall" type="text" name="number" value=""/>

Try in jsfiddle.


IT's good to intercept another events, like blur, change, focusout, etc. See jquery. Tks @Simen Echholt.


Explanation:

$(".longboxsmall").keyup

Jquery take every element with class longboxsmall and are ready to call a function on onkeyup event.

var value = $(this).val();
value = value.replace(/^(0*)/,"");
$(this).val(value);

This function uses a regex to replace every 0 in begin (^) of value.


Of course. Use one of input filter plugins (like this) with suitable regexp.


In order not to see the 0 in the input and then remove it you can use keypress:

$('.longboxsmall').on('keypress', function(e) { if (!$(this).val() && e.which == 48) return false; });


best way is prevent typing 0 in the first position while user is typing. we can achieve this by to use keyup event. by that we will avoid many case's like.

  1. end user first type say 123 and they add 0 in that like 0123.
  2. its prevent copy paste like 0123.

      $(document).on('keyup','#TextBoxID', function(event){
                    if($(this).val().match(/^0/)){
                      $(this).val('');
                      return false;
                  }
                }); 


$(".longboxsmall").keyup(function(){
    var value = $(this).val();
    value = value.replace(/[^(1*)]+|[^(0*)]+/,"");
    $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="longboxsmall" type="text" name="number" value=""/>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜