2

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 this??? Can I use Jquery??

5 Answers 5

4

$(".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.

Sign up to request clarification or add additional context in comments.

3 Comments

This can be ignored by pasting text with the mouse. Should also bind to mousedown/up and/or change
This only allows the user to type zero, and blocks them typing any further numbers. I want to stop them typing 0 as the first number in the string of numbers
@user342391 Sorry, but you're wrong. It allows to type anything. Just blocks 0 in first chars. Try here jsfiddle.net/s5B4B.
0

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

Comments

0

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

Comments

0

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

Comments

0

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

1 Comment

Please add some explanation to your code. Code only answers are discouraged on SO.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.