JQuery this () for textarea?

Hey! Another small issue (is this not a bug in jQuery?).

I have a text area:

<textarea>Something</textarea> 

I want to erase "Something" after clicking, like this:

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

Good. There are problems when I want to change the text “Something” ONLY when in my text box “Something”:

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

It works great for all different inputs, but not for textarea. And it works fine without an "if" loop, and what happens here? :)

Thanks a lot!

EDIT

So here is 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 except textarea.

+4
source share
3 answers

Are you sure that there are no spaces (or new lines) in the text box? something like that:

 <textarea> Something </textarea> 

If so, you can add .trim() to $(this).text() , this will remove leading and trailing spaces.

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

+2
source

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

If you use textareas content with JavaScript, use the value attribute ... the node content is for HTML presentation only.

+5
source

There are spaces after the word “Text” and before “. $ (This) .val () works in textareas, but the text in the text field was“ Text ”, not“ Text ”.

JSFiddle example

0
source

All Articles