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

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

This question is related to html textarea forms placeholder

The answer is


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.

_x000D_
_x000D_
<textarea class="textAreaMultiligne" _x000D_
          placeholder="Hello,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; This&nbsp;is&nbsp;multiligne&nbsp;example Have&nbsp;Fun&nbsp;&nbsp;&nbsp;&nbsp;"_x000D_
          rows="5" cols="35"></textarea>
_x000D_
_x000D_
_x000D_


With Vue.js:

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

This can apparently be done by just typing normally,

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

Yup! Line break seems to work."></textarea>
_x000D_
_x000D_
_x000D_


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


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>

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.


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

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>

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

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.

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

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

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.


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


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>

React:

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

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

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


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to textarea

Get user input from textarea Set textarea width to 100% in bootstrap modal Remove scrollbars from textarea Add a scrollbar to a <textarea> Remove all stylings (border, glow) from textarea How to clear text area with a button in html using javascript? Get value from text area What character represents a new line in a text area Count textarea characters More than 1 row in <Input type="textarea" />

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to placeholder

Keep placeholder text in UITextField on input in IOS HTML Input - already filled in text Add placeholder text inside UITextView in Swift? Bootstrap select dropdown list placeholder fail to change placeholder color with Bootstrap 3 Not showing placeholder for input type="date" field Use Font Awesome Icon in Placeholder How do I put hint in a asp:textbox How to support placeholder attribute in IE8 and 9 HTML5 image icon to input placeholder