Warm tip: This article is reproduced from stackoverflow.com, please click
html

Insert line break inside placeholder attribute of a textarea?

发布于 2020-03-30 21:13:48

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/

Questioner
amosrivera
Viewed
47
1,193 2013-09-27 03:26

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.