Search code examples
jquerykeypress

jquery keypress event firing a few times


Hi I have setup an autocomplete input text. I am trying to fire the event of reprinting the table on click of a btn and on a enter keypress. the btn click works fine and but the enter key press seems like it fires a few times before stoping (meaning the table flickers)

$('body').bind('keypress', function(e) {
        if(e.keyCode==13){
             var str = $('#Filter').val();
            $('#Table').fadeOut("slow").load('printShorts.server.php?Sortby=<?echo $sort;?>&dir=<?echo $direction;?>&filter='+encodeURIComponent(str)+'&usergroup=<?=$usergroup?>&no-cache=' + (new Date()).getTime() ).fadeIn("slow");
        }

}); 

it doesn't happen all the time and acts differntly in differnt browsers..


Solution

  • The keydown event in combination with an html textbox will not be sufficient to prevent it from being fired multiple times. You can see this behavior in action on the jquery demo section of the keydown event: http://api.jquery.com/keydown/

    One possible solution is to use the eventhandler "one" (see http://api.jquery.com/one/). Which ensures the event being handled only once:

    jQuery("#createNewProduct").one("keydown", function (e) {
        //Do Stuff
    });