开发者

jQuery this() for textarea?

开发者 https://www.devze.com 2023-01-16 10:56 出处:网络
Hey! Another small problem (isn\'t it a bug in jQuery?). I\'ve got a textarea like this: <textarea>Something</textarea>

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.


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.


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()


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

0

精彩评论

暂无评论...
验证码 换一张
取 消