Trouble with keyup in jQuery

860 Views Asked by At

Maybe noobie question about the keyup function, if the document is ready the div with id "testdiv" is empty that should not be. I want the testdiv empty if you really keyup. I have made a tiny script like this:

<script>
    $(document).ready(function(){  
        $('#test:input').keyup(function () {
            $('#testdiv').empty();              
        }).keyup(); 
    });
</script>
<input type="textfield" id="test" value="test123"/>
<div id="testdiv">Test</div>

Do I have to bind it? Sorry for this beginner question.

Regards,

Frank

2

There are 2 best solutions below

1
On BEST ANSWER
$('#test:input').keyup(function () {
    $('#testdiv').empty();              
}).keyup();

This says "bind a keyup handler, then immediately trigger it". The second keyup call triggers the handler. If you don't want it fired immediately, remove it:

$('#test:input').keyup(function () {
    $('#testdiv').empty();              
});
0
On

This line:

}).keyup();

...Immediately executes the function you defined for keyup. You don't want that.

$(document).ready(function(){  
    $('#test:input').keyup(function () {
        $('#testdiv').empty();              
    });
});