views:

43

answers:

3

Hey! Another small problem (isn't it a bug in jQuery?).

I've got a textarea like this:

<textarea>Something</textarea>

I want to erase "Something" after clicking, so:

$("textarea").click(function() {
     $(this).text("");
});

Ok so far. There are problems when I want to change the "Something" text ONLY when there's "Something" in my textarea:

$("textarea").click(
function() {
    if ($(this).text() === "Something") {
        $(this).text("");
        }
});

It works amazing for all different inputs, but not for textarea. And it works excellent without "if" loop, so what's going on here? :)

Thanks a lot!

EDIT

Ok, so here's my "real code":

$(".inp").click(
function(){
    if($(this).val() === "Text" || $(this).val() === "Name" || $(this).val() === "Mail" || $(this).val() === "Site" ) {
        $(this).val(""); 
    }
});

HTML:

<form>
<fieldset>
<input type="text" name="name" class="inp" value="Name" /> <br />
<input type="text" name="email" class="inp" value="Mail" /> <br />                             <input type="text" name="site" class="inp" value="Site" />  
<textarea rows="12" name="text" class="inp">Text </textarea>
</div>     

It works for all inputs, excepting textarea.

+4  A: 

Use .val("") instead of .text("")

If you're manipulating textareas content with JavaScript use the value attribute... the node contents are just for the HTML representation.

Luca Matteis
I've tried, vals work for other inputs but not for my textarea ;/
fomicz
+2  A: 

are you sure there aren't any whitespaces (or newlines) within the textarea? something like this:

<textarea>
Something
</textarea>

If this is the case you could append .trim() to $(this).text() this will remove leading and trailing whitespaces.

I've created the example above and it works. Something else: I would suggest using .focus() instead of .click, so it still works if the user is using the keyboard for navigation. Here is an example with .focus()

jigfox
ZOMG, WHITE SPACES! I'm so lame. Sorry, sorry, sorry! :) You're a genius :)
fomicz
sometimes you need another set of eyes to spot such errors. I'm glad I could help.
jigfox
A: 

There was whitespace after the "Text" and before the "". `$(this).val() works on textareas, but the text in the textarea was "Text ", not "Text".

JSFiddle Example

Rocket