Stop event on keyup in mootools doesn't work

502 views Asked by At

I'm trying to prevent non-numeric characters being entered in a text field. My code validates the characters but doesn't stop it being added to text box.

My code:

var isNumberKey = function(e){
    //alert(e.which);
    if (e.which > 31 && (e.which < 48 || e.which > 57)) 
        return false;   
    return true;
}

var isBackSpaceKey = function(e){
    return e.which == 8;
}

var isArrowKey = function(e) {
    return e.which >= 37 && e.which <= 40;
}

var inputs = $$('.numberOnly');
inputs.addEvent('keyup', function(e){
    console.log(e.which);
    if (!isNumberKey(e) && !isBackSpaceKey(e) && !isArrowKey(e)){
        e.stop();
        return false;
    }
    return true;
});

HTML:

<input name="t1" type="text" class="numberOnly" id="t1"/>
1

There are 1 answers

4
pleasedontbelong On BEST ANSWER

you should use the keydown event instead of the keyup. I'd do it like this:

var inputs = $$('.numberOnly');
inputs.addEvent('keydown', function(e){
    if (e.code >= 48 && e.code <= 57 ){
        return true;
    }
    e.stop();
    return false;
});

http://jsfiddle.net/TsAkb/

Hope this helps

EDIT:

Maybe you'd want to allow the "tab" key ,the "enter" key and the "backspace" too =P