2

my "label" is inside the input, so i want to empty the field when the user click and if its empty the "label" is back again

     $('#name').focus(function() {
        if ($(this).val()=="Your name") { $(this).val(""); }
    }).blur(function() {
        if ($(this).val()=="") { $(this).val("Your name") }
    });

and this would be done to 3 or more fields, there's any better aprouch? without using plugins, just jquery

3
  • You also need to account for what happens if they leave the field blank and submit the form. Commented Mar 3, 2011 at 19:33
  • its a ajax reply, i do php validation only in this case Commented Mar 3, 2011 at 19:38
  • stackoverflow.com/questions/5120257/… Commented Mar 3, 2011 at 19:47

2 Answers 2

5

I think your method is probably almost as concise as it's going to get, but it's worth noting that html5 offers the placeholder attribute to input tags:

<input type="text" placeholder="Your name." />

JS Fiddle demo.

This is, of course, yet to make its way through to the non-modern browsers...

Sign up to request clarification or add additional context in comments.

Comments

2

If you want to make it work with the other fields easily you could remove the check and place the Your name value on the title attribute of the field.

$('.waterMarkInput').focus(function() {
  if ($(this).val()==$(this).attr("title")) { $(this).val(""); }
}).blur(function() {
  if ($(this).val()=="") { $(this).val($(this).attr("title")); }
});

And then your input fields could look like this:

<input type="text" value="" class="waterMarkInput" title="Your name"/>

2 Comments

thanks! a little fix: if ($(this).val()=="") { $(this).val($(this).attr("title")); }
I started with this script and added the ability to simply use the current value of the field, so there is no need to have a title attribute. Also added the necessary deferred executiion. <pre> $(document).ready(function(){ $('.inlineLabel').focus(function() { if ($(this).attr("initial") == undefined) { $(this).attr("initial",$(this).val()); } if ($(this).val() == $(this).attr("initial")) { $(this).val(""); } }).blur(function() { if ($(this).val() == "") { $(this).val($(this).attr("initial")); } }); }); </pre>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.