Search code examples
javascriptmootoolstextinputonkeyup

how to empty input field after start typing


I am trying to make an input box where the input box gets empty once you start typing. (Not on focus). I tried using keyup event on mootools, but the flow is not seamless. it takes some time to erase the input field. here is the code

document.addEvent('domready', function(e) {
$('inputBox').addEvent('keyup', function() {
    if(inputBox.value != inputBox.defaultValue){
        inputBox.value = '';
        $('inputBox').removeEvents('keyup');    
    }
});
});

What is best way to do it such that it can behave better?


Solution

  • As Remon said, you can bind to a keydown event and you will not have any delay but then you can't do a comparison with the default value as when the key is pressed down, the value will be as same (the value changed once you get the key up).

    This will be the code with keydown:

    document.addEvent('domready', function(e) {
        $('inputBox').addEvent('keydown', function() {
            this.set('value', '').removeEvents('keydown');
        });
    });
    

    If you want to do a comparison as you did in your initial code, then you will need to use keyup but it will have a small delay.

    Here is your code a bit optimized and working:

    document.addEvent('domready', function(e) {
        $('inputBox').addEvent('keyup', function(ev) {
            if(this.value != this.defaultValue){
                this.set('value', ev.key).removeEvents('keyup');
            }
        });
    });​
    

    I hope this answer your question :)