0

This is probably stupidity on my part, but where am I going wrong with this?

$(function() { $('textarea#comment').each(function() { var $txt = $(this).val(); $(this).bind('focus', function() { if($(this).val($txt)) { $(this).val(''); } }); }); }); 

Basically on focus I want to check if the value is the default value in this case 'Enter your comment', then if it is change the value to nothing.

Anyone know how to do this? I'm guessing its relatively simple. What the code does at the moment is removes any value.

3 Answers 3

1

Ok first off you should only have one tag with the id of comment since ids are supposed to be unique, but if we go with your code you have to setup a default value first like this:

<textarea id="comment">Enter text here</textarea> 

Now the javascript:

 (function() { $('textarea#comment').each(function() { var $txt = $(this).val(); //alert($txt); $(this).bind('focus', function() { if($(this).val() === this.defaultValue) { $(this).val(''); } }); }); })(); 

The self executing function syntax has been corrected here and should be as follow:

(function () { // my code here })(); 

and for default value use:

this.defaulValue; // works for input boxes as well 

Hope it helps. Cheers

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

Comments

0

jquery_example plugin do exactly what you need. You may have a look at its source code and get some inspiration. Or you can store the default value as meta-data on the tag and check against it on change event of the textarea tag.

Comments

0

try

$('#comment').live('click change focus', function() { var $txt = $(this).val(); if($txt == 'Enter your comment' ); $(this).val(''); }); 

DEMO

3 Comments

Not what I'm after, it clears the value no matter what the value is. Thanks for the effort though.
ok then comment initial two lines..this will clear whatever is written.see here : jsfiddle.net/Em4je/2
Clearing 'no matter what the value is' was not what i was after. Thanks anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.