jQuery keypress event problem

4.5k views Asked by At

I have a function (filterLeads) that I wish to call both when a form field is moved away from (blur) and when the enter key is pressed within a form field.

$('#filter input, #filter select').blur(filterLeads);
$('#filter input, #filter select').keypress(function(e){if(e.which == 13) {filterLeads();}});

The blur works correctly but I am having a problem with the keypress event. The event does not appear to be fired unless something comes before the call to filterLeads(); for example:

$('#filter input, #filter select').keypress(function(e){if(e.which == 13) {alert(e.which);filterLeads();}});

This correctly calls filterLeads() after acknowledging the alert (which shows the correct key code).

Any ideas? (Browser FF 3.0)

3

There are 3 answers

2
Boldewyn On

Just a try: You should return false; from within the anonymous function, because else the form (if there is one) containing the fields gets submitted and the page is reloaded.

If filterLeads expects the event as parameter, don't forget to write: filterLeads(e).

And if nothing else helps: Fire blur():

$('#filter input, #filter select').keypress(function(e){$(e.target).blur();});

(jQuery-fied, because there could be custom jQuery events attached).

1
krcko On

just add e.preventDefault(); inside your event handler, like this:

  $('#filter input, #filter select').keypress(function(e){if(e.which == 13) {filterLeads(); e.preventDefault(); }});
1
Mottie On

I'm not sure why you are only targeting FF... but you should also include all non-FF browsers by using e.keyCode. Also keypress may not be best event to use according to this information.

Try something like this:

$("#filter input, #filter select").keyup(function(e){
 var key = (e.which) ? e.which : e.keyCode;
 if( key == 13 ){ filterLeads(e) }
});