Search code examples
jquerytextareaonbluronfocus

Can I use jquery to blank textarea fields or ajax like input boxes?


I always use this snippet in my work:

<input type="text" onblur="if (this.value=='') { this.value='your email'; }" onfocus="if (this.value == 'your email') { this.value=''; }" value="your email" /> 

Basically it will show a text box with "your email" as the value, when the clicks the text input box - the value becomes blank.. thus they type their email.. if they don't type an email it will reset back to the "your email".

I want to do this or similar with textarea and convert it to jQuery (also the above code in jQuery)?

<textarea name="msg">Message:</textarea><br />

Solution

  • This ought to do the trick:

    Will work for both inputs and textareas -- Whatever default you set for each will persist. Use as is.

    See Fiddle here : http://jsfiddle.net/leifparker/DvqYU/2/

    (This pulls and stores the default value in a data attribute)

    HTML

    <textarea>I love bananas ..</textarea>
    <textarea>How about you?</textarea>
    <input type="text" value="Time for a bath ..">
    <input type="text" value=".. because I smell">
    

    JS

    $('textarea, input[type=text]')
        .each(function(){ 
            $(this).data('defaultText', $(this).val());
        })
        .focus(function(){
            if ($(this).val()==$(this).data('defaultText')) $(this).val('');
        })
        .blur(function(){
            if ($(this).val()=='') $(this).val($(this).data('defaultText'));
        });
    


    EDIT:

    An alternative brought up by ANeves, and which makes use of the HTML5 placeholder attribute is below. If you don't care about old browsers, you can use the placeholder HTML on its own (and it works natively, with results similar to the JS above), or otherwise, as below, you'll need to add a JS fallback.

    Fiddle here : http://jsfiddle.net/leifparker/DvqYU/14/

    HTML

    <textarea placeholder="A few words about yourself"></textarea>
    <textarea placeholder=".. and a few more about your mangy cat."></textarea>
    <input type="text" placeholder="Your Awesome City">
    <input type="email" placeholder="rickastin@youjustgot.com">
    

    JS

    function hasPlaceholderSupport() {
      var input = document.createElement('input');
      return ('placeholder' in input);
    }
    
    if (!hasPlaceholderSupport()){
        $('textarea, input[type=text], input[type=email]')
            .each(function(){
                if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
            })
            .focus(function(){
                if ($(this).val()==$(this).attr('placeholder')) $(this).val('');
            })
            .blur(function(){
                if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
            });
    }