jQuery Form Submit Handling with Return Key

If you have ever done any stuff with jquery/javascript that redirects you upon submitting a form, you’ll have noticed that the return key slips through the net and doesn’t obviously trigger the click event.
I’ve dealt with this nonsense plenty of times but i always end up hunting through my code to find it again. So to spare my sanity, I’m putting it here!

$('#submit').click(function(e){
 e.preventDefault();
 var name = $('#search').val();
 window.location.href = '/some/url/'+name;
 });
$("#search").keyup(function(event){
 if(event.keyCode == 13){
 $("#submit").click();
 }
 });
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s