views:

702

answers:

3

Hi,

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)

+1  A: 

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).

Boldewyn
That doesn't seem to work. The page isn't being reloaded when the enter is pressed so I don't think the form action is being triggered (there is no submit button).
Tom
Try to put your action on the keyup event. Any changes?
Boldewyn
A: 

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

  $('#filter input, #filter select').keypress(function(e){if(e.which == 13) {filterLeads(); e.preventDefault(); }});
krcko
This is basically the same as returning false, if there are no other event handlers registered.
Boldewyn
Yeh, unfortunately that isn't working either.
Tom
i've meant preventDefault(), instead of stopPropagation(), sorry...
krcko
i've changed the answer...
krcko
+1  A: 

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) }
});
fudgey
The code is actually being used in an internal web app for the company that I work for and we can guarantee that Firefox will be used to access it. Having said that I am very keen to write cross browser code and that information is very useful - thanks :)
Tom