开发者

How can I fake placeholder text using JavaScript?

I have a very small form where a user can enter their zip code into an input field and either hit e开发者_高级运维nter, 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?


Put a conditional inside your blur function.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜