Displaying error/success messages inside an input field
I have an input field that asks for an email address followed by a submit button. Here is the code associated with that:
HTML
<div class="email">
<form action="handler.php" method="post" id="hgb-signup">
<input type="text" name="email" id="email" value="Enter your email address">
<input type="submit" name="submit" id="submit" value="»" />
</form>
</div>
JAVASCRIPT
Event.observe(window, 'load', function() {
jQuery('#email').focus(function() {
jQuery(this).val('');
});
jQuery("#hgb-signup").submit(function(e){
var dataString = jQuery(this).serialize();
jQuery('#email').val('Sending... please wait...');
jQuery.getJSON('handler.php?callba开发者_开发知识库ck=?', {
"sent_data": dataString },
function(received_data) {
jQuery('#email').val(received_data.message);
}
);
e.preventDefault();
});
});
Right now, when the page loads the #email
input field reads "Enter your email address". When you click on the submit button, it overwrites the #email
value with "Sending... please wait..." and depending on whether there's been a problem or the submission was successful, there will be a respective message inside the #email
field indicating such. Now, when I click inside the input field, the "Enter your email address" text disappears .val('')
, and when I click outside the field, that message is still gone. I initially had a .blur()
that put the message back, which is the desired result, however, when users would enter their email address and hit submit, it would submit "Enter your email address" and not the actual email address, because when you hit the submit button .blur()
was called.
Now knowing what the goal is, is there a .blur() alternative and if not, how do I best handle this situation?
Basically, here's what I'm looking for:
The #email field should read "Enter your email address" at any given time when the cursor is not inside the field and should come back when the cursor leaves the field, but I would like the error/success message to stay in there after the form has been submitted, unless the user clicks back inside the field and leaves, then it can say "Enter your email address" again.
Thanks!
Use .blur()
, but check the val()
first. Replace with "Enter your email"
only when it's empty
jQuery('#email').blur(function() {
var $this = jQuery(this);
if ($this.val() == '') $this.val('Enter your email');
});
Here's a jsfiddle for you, you can check it out. I also added a check to focus()
handler so it would not remove contents when you click on an input field after entering your email.
精彩评论