views:

484

answers:

2

I have a very small form where a user can enter their zip code into an input field and either hit enter, or click the submit button to submit their zip code to our database which returns search results to the page. Everything works fine using the Enter key. Things don't work so well when the user clicks on the Submit button...

The reason is because the default text of the Zip Code field is "Zip Code". When the element has focus, using jQuery, I set the val() to ''.

$( 'div.program-locator input#zipcode' ).focus(function() {
  $( this ).val( '' );
});

When the focus leaves the field, I use the .blur event to set the field back to "Zip Code".

$( 'div.program-locator input#zipcode' ).blur(function() {
  $( this ).val( 'Zip Code' );
});

The problem lies with the fact that when the user clicks on the Submit button, the .blur event is called, setting the value of the Zip Code field to "Zip Code". Yuck.

How can I get around this? Is there a way to not call the #zipcode.blur event until after I call the #submit.click event?

A: 

I would say your simplest solution is:

$( 'div.program-locator input#zipcode' ).blur(function() {
  setTimeout(function() { $('#zipcode').val( 'Zip Code' ); }, 10);
});

Adds a slight delay to the reset so the submit functions can fire off. The time doesn't matter, just so long as it queues the function to run after the submit handler has completed.

Nick Craver
+1  A: 

Put a conditional inside your blur function.

if($(this).val()==""){
    $(this).val("Zip Code");
}
Jeremy