Question

How to easily prevent 0 from being the first char entered in a textbox with JavaScript? I want something like the .Net OnKeyDown(). When the user presses 0 key for the first char to be prevented

e.Handled = true;

Why doesnt this work?

function PreventFirstCharZero()
{
var TB = document.getElementById("idbox").value;
var TextLength = TB.value.length;

if (48 == event.keyCode && 0 == TextLength)
{
    event.preventDefault();
}
}

This doesn't work

function PreventFirstCharZero()
{
    if ('0' == document.getElementById("idbox")[0].value)
    {
        event.preventDefault();
    }
}
Was it helpful?

Solution 4

try this!

$("#input").on("keypress keyup",function(){
    if($(this).val() == '0'){
      $(this).val('');  
    }
});

jsfiddle

OTHER TIPS

Try this http://jsbin.com/sanoz/4/edit

document.getElementById('input').addEventListener('keyup', function(){
    if(this.value.charAt(0) === '0')
        this.value = this.value.slice(1);
});

You can prevent paste using:

<input onpaste="return false;" id="input"/>

or have a look at this: detecting change in a text input box using jquery/javascript

Short and sweet, pure javascript one-liner:

<input onkeyup="if (event.srcElement.value.charAt(0) == '0') { event.srcElement.value = event.srcElement.value.slice(1); }" />

JsFiddle

To be honnest, prevent a key to be entered isn't a good solution since you can always copy/past and the event will not trigger.

If i may suggest you an other solution, use change (or blur since change doesnt work in all browser apparently) event and remove the first char if it's a 0:

document.getElementById('noZero').addEventListener('blur', checkZero)

function checkZero(){
    var val = this.value;
    if(val.charAt(0) === '0')
        this.value = val.slice(1), checkZero.call(this);
}

http://jsfiddle.net/F5ZSA/6/


If you absolutly want a key event, you can change 'change' to 'keyup' and it will work, but will still be able to rightclick and paste without triggering the keyup event;

<input type="text" onKeyUp="Prevent(this.value)" id="testInput" />

javascript

function Prevent(value) {
    var x = document.getElementById("testInput");
    if (value == 'O') {
        x.value = '';
    }
}

Demo Fiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top