views:

325

answers:

8

Im using a simple form with a textarea, when the users clicks onto the textarea I want the contents of the textarea to be cleared.

Is this possible?

+6  A: 
$('textarea#someTextarea').focus(function() {
   $(this).val('');
});
Jacob Relkin
+1  A: 
jQuery(function($){
    $("textarea").focus(function(){
        $(this).val("");
    });
});
Álvaro G. Vicario
+2  A: 

Are you sure you don't want to remove only default text? In my experience those kind of behaviors can be really intrusive...

torkildr
A: 
$('textarea#someTextarea').focus(function() {
   this.value = "";
});
Pranay Rana
A: 

My suggestion is that you only remove the initial default content on the first focus. On subsequent focuses, you risk removing user content. To achieve this, simply .unbind() the focus handler after the first click:

$("textarea").focus(function(event) {

      // Erase text from inside textarea
    $(this).text("");

      // Disable text erase
    $(this).unbind(event);
});

jsFiddle example



As a note, since you are using a textarea which has open and closing tags, you can can use $(this).text(""); or $(this).html("");... and, since the text inside a textarea is its value you can also use $(this).val(""); and $(this).attr("value", ""); or even this.value = "";.

Peter Ajtai
+1  A: 

If you only want to delete the default text (if it exists), try this:

$("textarea").focus(function() {

    if( $(this).text() == "Default Text" ) {
        $(this).text("");
    }

});

By testing for the default text, you will not clear user entered text if they return to the textarea.

If you want to reinsert the default text after they leave (if they do not input any text), do this:

$("textarea").blur(function() {

    if( $(this).text() == "" ) {
        $(this).text("Default Text");
    }

});

Of course, the above examples assume you begin with the following markup:

<textarea>Default Text</textarea>

If you want to use placeholder text semantically you can use the new HTML5 property:

<textarea placeholder="Default Text"></textarea>

Although this will only be supported in capable browsers. But it has the added advantage of not submitting the placeholder text on form submission.

kingjeffrey
A: 

Something like this?

$('textarea#myTextarea').focus(function() {
   if ($(this).val() == 'default text') {
      $(this).val('');
   }
});
redwall_hp
A: 

There are a number of usability drawbacks to using the value for help texts: the user might inadvertently submit it, the browser might overwrite it, the user might start typing before your script has run etc. The proper way is positioning a label over the input field, which is somewhat more complicated than just setting the value, but fortunately there's a bunch of plugins (e.g. labelify) which do th hard part for you.

Tgr