Search code examples
html

Insert line break inside placeholder attribute of a textarea?


I have tried a few approaches but none worked. Does anyone know a the nifty trick to get around this?

<textarea placeholder='This is a line \n this should be a new line'></textarea>

<textarea placeholder='This is a line     
should this be a new line?'></textarea> <!-- this works in chrome apparently -->

UPDATE: It doesn't work in chrome. It was just the textarea width.

See: http://jsfiddle.net/pdXRx/


Solution

  • What you could do is add the text as value, which respects the line break \n.

    $('textarea').attr('value', 'This is a line \nthis should be a new line');
    

    Then you could remove it on focus and apply it back (if empty) on blur. Something like this

    var placeholder = 'This is a line \nthis should be a new line';
    $('textarea').attr('value', placeholder);
    
    $('textarea').focus(function(){
        if($(this).val() === placeholder){
            $(this).attr('value', '');
        }
    });
    
    $('textarea').blur(function(){
        if($(this).val() ===''){
            $(this).attr('value', placeholder);
        }    
    });
    

    Example: http://jsfiddle.net/airandfingers/pdXRx/247/

    Not pure CSS and not clean but does the trick.