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

HtmlTextareaFormsPlaceholder

Html Problem Overview


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});

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

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.

Solution 3 - Html

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>

Solution 4 - Html

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.

Solution 5 - Html

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

Solution 6 - Html

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>

Solution 7 - Html

React:

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

placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}

Solution 8 - Html

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>

Solution 9 - Html

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 ;)

Solution 10 - Html

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>

Solution 11 - Html

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

Solution 12 - Html

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>

Solution 13 - Html

With Vue.js:

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

Solution 14 - Html

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;
}

Solution 15 - Html

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.

Solution 16 - Html

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'));
              }
            }
          }
        }
      };
    });
}());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionat.View Question on Stackoverflow
Solution 1 - HtmlIonuț G. StanView Answer on Stackoverflow
Solution 2 - HtmlCyrbilView Answer on Stackoverflow
Solution 3 - HtmlThomas Hunter IIView Answer on Stackoverflow
Solution 4 - HtmlGottoxView Answer on Stackoverflow
Solution 5 - HtmlLaundroMatView Answer on Stackoverflow
Solution 6 - Htmlross_trohaView Answer on Stackoverflow
Solution 7 - Htmlfiretiger77View Answer on Stackoverflow
Solution 8 - HtmlUzair HayatView Answer on Stackoverflow
Solution 9 - HtmlSilent PenguinView Answer on Stackoverflow
Solution 10 - HtmlKrzysiekView Answer on Stackoverflow
Solution 11 - HtmlVladView Answer on Stackoverflow
Solution 12 - HtmlJeffrey NeoView Answer on Stackoverflow
Solution 13 - HtmlBenoit BlanchonView Answer on Stackoverflow
Solution 14 - HtmlMiha PirnatView Answer on Stackoverflow
Solution 15 - HtmlJP DamstraView Answer on Stackoverflow
Solution 16 - HtmlYura FedorivView Answer on Stackoverflow