Can you have multiline HTML5 placeholder text in a <textarea>?
Asked Answered
A

17

173

I have ghost text in textfields that disappear when you focus on them using HTML5's placeholder attribute:

<input type="text" name="email" placeholder="Enter email"/>

I want to use that same mechanism to have multiline placeholder text in a textarea, maybe something like this:

<textarea name="story" placeholder="Enter story\n next line\n more"></textarea>

But those \ns show up in the text and don't cause newlines... Is there a way to have a multiline placeholder?

UPDATE: The only way I got this to work was utilizing the jQuery Watermark plugin, which accepts HTML in the placeholder text:

$('.textarea_class').watermark('Enter story<br/> * newline', {fallback: false});
Another answered 25/8, 2011 at 11:0 Comment(5)
IE seems to handle it properly. Firefox OTOH just ignores the newlinesMarr
#7313123 is a very similar question with good answers too.Goshen
if you're encountering this and using js to set the value check css white-space to make sure it's set correctly e.g. pre-wrapRomeoromeon
From that other question: &#10; works everywhere except Safari.Mawkish
as of this time, you may add a placeholder string with \n between lines, or a native es6 string in with multiple lines delimited this way, and you also need to style the textarea element with white-space: pre;.Stationmaster
C
87

For <textarea>s the spec specifically outlines that carriage returns + line breaks in the placeholder attribute MUST be rendered as linebreaks by the browser.

User agents should present this hint to the user when the element's value is the empty string and the control is not focused (e.g. by displaying it inside a blank unfocused control). All U+000D CARRIAGE RETURN U+000A LINE FEED character pairs (CRLF) in the hint, as well as all other U+000D CARRIAGE RETURN (CR) and U+000A LINE FEED (LF) characters in the hint, must be treated as line breaks when rendering the hint.

Also reflected on MDN: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea#attr-placeholder

FWIW, when I try on Chrome 63.0.3239.132, it does indeed work as it says it should.

Coaly answered 25/8, 2011 at 11:27 Comment(1)
except that the title attribute does not behave the same way i.e. it does not show ghost content. in fact it would be perfectly appropriate for placeholders to support multiple lines for text areas since text areas are multi-line creatures. pity the spec doesn't allow it. I guess the hacks will have to do. sighMarr
L
78

On most (see details below) browsers, editing the placeholder in javascript allows multiline placeholder. As it has been said, it's not compliant with the specification and you shouldn't expect it to work in the future (edit: it does work).

This example replaces all multiline textarea's placeholder.

var textAreas = document.getElementsByTagName('textarea');

Array.prototype.forEach.call(textAreas, function(elem) {
    elem.placeholder = elem.placeholder.replace(/\\n/g, '\n');
});
<textarea class="textAreaMultiline" 
          placeholder="Hello, \nThis is multiline example \n\nHave Fun"
          rows="5" cols="35"></textarea>

JsFiddle snippet.

Expected result

Expected result


Based on comments it seems some browser accepts this hack and others don't.
This is the results of tests I ran (with browsertshots and browserstack)

  • Chrome: >= 35.0.1916.69
  • Firefox: >= 35.0 (results varies on platform)
  • IE: >= 10
  • KHTML based browsers: 4.8
  • Safari: No (tested = Safari 8.0.6 Mac OS X 10.8)
  • Opera: No (tested <= 15.0.1147.72)

Fused with theses statistics, this means that it works on about 88.7% of currently (Oct 2015) used browsers.

Update: Today, it works on at least 94.4% of currently (July 2018) used browsers.

Lavolta answered 12/8, 2014 at 10:21 Comment(13)
That jsfiddle example doesn't work at all... It's only multilined because the size of the textarea.Orlov
There's a typo, but I can't edit because StackOverflow give me this "Edits must be at least 6 characters" error. Your class should be multiline not multiligneChaperon
@sebnukem: It works on most browsers that i had test out. And it's not a matter of textarea's size. Can you provide more information on the issue you had ?Lavolta
Doesn't work on safari it seems... - the \n disappears but everything is on a single lineTeddy
Hey @Teddy thx for reporting it, I update my answer with tests for various browsers.Lavolta
Firefox 39, Windows 8, couldn't make it work (through Rails .erb) :(Subauricular
@CyrilDD: The best option is to use a superposition of textarea & div, using events to simulate a multiline placeholder. These posts are just magic hack that are against the spec and are not guaranteed to work.Lavolta
True, FF does not support it anymore for a while, all platforms.Lavolta
@DanielLoureiro Fixed :)Eckert
It doesn't seem to work on the current Google Chrome for IOS version 70.0.3538.75. All the '\n' are replaced correctly, but the rendering is no character. For example placeholder="DATE\nRANGE" is rendered looking like "DATERANGE".Sidon
@Jroonk: I can confirm that. It's not due to chrome but to Apple forcing any browser to uses its IOS's WKWebView. Subsequently, any browser on IOS won't render this hack properly until WKWebView does.Lavolta
works on at least 94.4% of browsers. --- It doesn't work on iPhone browsers which I imagine is more than just 5.6% of browsers.Scorpaenid
@AlbertRenshaw as you can see en.m.wikipedia.org/wiki/Usage_share_of_web_browsers. The problem is finding statistics that show WebKit and not Firefox/chrome/safari...Lavolta
C
62

I find that if you use a lot of spaces, the browser will wrap it properly. Don't worry about using an exact number of spaces, just throw a lot in there, and the browser should properly wrap to the first non space character on the next line.

<textarea name="address" placeholder="1313 Mockingbird Ln         Saginaw, MI 45100"></textarea>
Chlori answered 12/1, 2012 at 23:6 Comment(3)
Yep multiline placeholders are not supported crossbrowser, have found the latest safari does support but is definitely not supported on IOS5Colostrum
that doesn't work for me in either IE nor Firefox Windows. it just inserts the spaces I asked for it toMarr
Chrome 37 is displaying placeholder text in a textarea without stripping the newlines. Does anyone know what the name of the 'feature' is so that I can a) look for it, and b) test for it?Garb
C
25

According to MDN,

Carriage returns or line-feeds within the placeholder text must be treated as line breaks when rendering the hint.

This means that if you just jump to a new line, it should be rendered correctly. I.e.

<textarea placeholder="The car horn plays La Cucaracha.
You can choose your own color as long as it's black.
The GPS has the voice of Darth Vader.
"></textarea> 

should render like this:

enter image description here

Cushion answered 21/1, 2019 at 8:38 Comment(2)
Works in the latest Chrome.Roshan
This method is the easiest to implement. It honors tabs too.Junie
M
23

There is actual a hack which makes it possible to add multiline placeholders in Webkit browsers, Chrome used to work but in more recent versions they removed it:


First add the first line of your placeholder to the html5 as usual

<textarea id="text1" placeholder="Line 1" rows="10"></textarea>

then add the rest of the line by css:

#text1::-webkit-input-placeholder::after {
    display:block;
    content:"Line 2\A Line 3";
}

If you want to keep your lines at one place you can try the following. The downside of this is that other browsers than chrome, safari, webkit-etc. don't even show the first line:

<textarea id="text2" placeholder="." rows="10"></textarea>​

then add the rest of the line by css:

#text2::-webkit-input-placeholder{
    color:transparent;
}

#text2::-webkit-input-placeholder::before {
    color:#666;
    content:"Line 1\A Line 2\A Line 3\A";
}

Demo Fiddle

It would be very great, if s.o. could get a similar demo working on Firefox.

Marketable answered 14/10, 2012 at 21:36 Comment(2)
thanks for providing the fiddle link. it makes it easy to verify behaviour in various browsers. on IE 10 both versions fail, as well as on FF 12 (Windows). pity that. Safari 6.1 works :(Marr
No longer works in Chrome - for a long time now, I'd assume.Emoryemote
D
11

React:

If you are using React, you can do it as follows:

placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}
Dail answered 8/6, 2018 at 22:17 Comment(1)
I couldn't get this working in React 18. Not sure why.Waggoner
N
9

If you're using AngularJS, you can simply use braces to place whatever you'd like in it: Here's a fiddle.

<textarea rows="6" cols="45" placeholder="{{'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}}"></textarea>
Newspaper answered 30/6, 2016 at 16:29 Comment(1)
I am using similar approach but it is not working in Safari and FirefoxSiskin
T
8

This can apparently be done by just typing normally,

<textarea name="" id="" placeholder="Hello awesome world. I will break line now

Yup! Line break seems to work."></textarea>
Thomasina answered 18/10, 2020 at 17:30 Comment(1)
Ok but it takes all the second line tabs too if the element is indentedAvens
S
3

The html5 spec expressly rejects new lines in the place holder field. Versions of Webkit /will/ insert new lines when presented with line feeds in the placeholder, however this is incorrect behaviour and should not be relied upon.

I guess paragraphs aren't brief enough for w3 ;)

Sclerotic answered 25/8, 2011 at 11:27 Comment(3)
Webkit's behavior is not incorrect since the specification does not say what must happen if CR/LF do exist.Cleanly
@Cleanly It does now, it says "User agents should present this hint to the user, after having stripped line breaks from it...". It says this about stripping line breaks: "When a user agent is to strip line breaks from a string, the user agent must remove any "LF" (U+000A) and "CR" (U+000D) characters from that string.".Orin
This answer is no longer true. The spec now expressly requires that linebreaks in the placeholder be rendered as linebreaks.Infatuate
T
3

With Vue.js:

<textarea name="story" :placeholder="'Enter story\n next line\n more'"></textarea>
Tita answered 3/8, 2020 at 16:0 Comment(1)
another way :placeholder="`/robots.txt \r\n /google-analytics-auth.html`"Aphotic
F
2

If your textarea have a static width you can use combination of non-breaking space and automatic textarea wrapping. Just replace spaces to nbsp for every line and make sure that two neighbour lines can't fit into one. In practice line length > cols/2.

This isn't the best way, but could be the only cross-browser solution.

<textarea class="textAreaMultiligne" 
          placeholder="Hello,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This&nbsp;is&nbsp;multiligne&nbsp;example Have&nbsp;Fun&nbsp;&nbsp;&nbsp;&nbsp;"
          rows="5" cols="35"></textarea>
Fraunhofer answered 12/6, 2015 at 10:38 Comment(0)
V
2

in php with function chr(13) :

echo '<textarea class="form-control" rows="5" style="width:100%;" name="responsable" placeholder="NOM prénom du responsable légal'.chr(13).'Adresse'.chr(13).'CP VILLE'.chr(13).'Téléphone'.chr(13).'Adresse de messagerie" id="responsable"></textarea>';

The ASCII character code 13 chr(13) is called a Carriage Return or CR

Vibrator answered 1/6, 2018 at 12:29 Comment(2)
This worked for me but can you please explain the logic or theory behind it?Northeast
This is complete nonsense. PHP won't parse the chr(13) tags with this syntax; even if it did, this would be just a more complicated way of just putting \r into the string; and obviously, this ignores all the previously stated compatibility problems and, indeed, the actual question.Piddling
F
1

You can try using CSS, it works for me. The attribute placeholder=" " is required here.

<textarea id="myID" placeholder=" "></textarea>
<style>
#myID::-webkit-input-placeholder::before {
    content: "1st line...\A2nd line...\A3rd line...";
}
</style>
Fulkerson answered 8/5, 2014 at 12:9 Comment(0)
K
0

Bootstrap + contenteditable + multiline placeholder

Demo: https://jsfiddle.net/39mptojs/4/

based on the @cyrbil and @daniel answer

Using Bootstrap, jQuery and https://github.com/gr2m/bootstrap-expandable-input to enable placeholder in contenteditable.

Using "placeholder replace" javascript and adding "white-space: pre" to css, multiline placeholder is shown.

Html:

<div class="form-group">
    <label for="exampleContenteditable">Example contenteditable</label>
    <div id="exampleContenteditable" contenteditable="true" placeholder="test\nmultiple line\nhere\n\nTested on Windows in Chrome 41, Firefox 36, IE 11, Safari 5.1.7 ...\nCredits StackOveflow: .placeholder.replace() trick, white-space:pre" class="form-control">
    </div>
</div>

Javascript:

$(document).ready(function() {
    $('div[contenteditable="true"]').each(function() {
        var s=$(this).attr('placeholder');
        if (s) {
            var s1=s.replace(/\\n/g, String.fromCharCode(10));
            $(this).attr('placeholder',s1);
        }
    });
});

Css:

.form-control[contenteditable="true"] {
    border:1px solid rgb(238, 238, 238);
    padding:3px 3px 3px 3px;
    white-space: pre !important;
    height:auto !important;
    min-height:38px;
}
.form-control[contenteditable="true"]:focus {
    border-color:#66afe9;
}
Keeter answered 9/4, 2015 at 11:27 Comment(0)
S
0

If you're using a framework like Aurelia that allows one to bind view-model properties to HTML5 element properties, then you can do the following:

<textarea placeholder.bind="placeholder"></textarea>
export class MyClass {
  placeholder = 'This is a \r\n multiline placeholder.'
}

In this case the carriage return and line feed is respected when bound to the element.

Shinn answered 10/4, 2021 at 20:25 Comment(0)
S
0

as of this time, you may set a placeholder string with \n between lines, or use a native es6 string like:

let str = `with
     multiple lines
     delimited this way`;

you also need to style the textarea element with white-space: pre;.

Stationmaster answered 23/2 at 23:42 Comment(0)
D
-1

Watermark solution in the original post works great. Thanks for it. In case anyone needs it, here is an angular directive for it.

(function () {
  'use strict';

  angular.module('app')
    .directive('placeholder', function () {
      return {
        restrict: 'A',
        link:     function (scope, element, attributes) {
          if (element.prop('nodeName') === 'TEXTAREA') {
            var placeholderText = attributes.placeholder.trim();

            if (placeholderText.length) {
              // support for both '\n' symbol and an actual newline in the placeholder element
              var placeholderLines = Array.prototype.concat
                .apply([], placeholderText.split('\n').map(line => line.split('\\n')))
                .map(line => line.trim());

              if (placeholderLines.length > 1) {
                element.watermark(placeholderLines.join('<br>\n'));
              }
            }
          }
        }
      };
    });
}());
Dyslogia answered 30/3, 2017 at 13:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.