tags:

views:

40

answers:

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??

A: 

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.

Topera
This can be ignored by pasting text with the mouse. Should also bind to `mousedown/up` and/or `change`
Simen Echholt
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 http://jsfiddle.net/s5B4B/.
Topera
A: 

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

Chaotic_one