Insert line break inside placeholder attribute of a textarea?
Asked Answered
S

25

277

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/

Selfreproach answered 5/9, 2011 at 20:50 Comment(8)
If using PHP, you can put <?="\n"?> as a new lineFestoon
Just add &#10; in the placeholder attribute, like <textarea placeholder="This is a line&#10;This is another one"></textarea>. The answer is down below.Scyphozoan
@Scyphozoan this works in Chrome, IE but not in Firefox and Safari.Mesoblast
@Mesoblast I have tested it a minute ago in Firefox 60.0.2 and now it works. Maybe it would work in most browsers now.Zealand
It's 2020 and still no solution for Safari?Commutative
Does this answer your question? Can you have multiline HTML5 placeholder text in a <textarea>?Coltin
If using PHP, then you can also use <?='This is a line'.PHP_EOL.'This should be a new line';?>.Hew
Does this answer your question? How can I use a carriage return in a HTML tooltip?Anglesite
S
59

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.

Subject answered 5/9, 2011 at 22:47 Comment(10)
i could certainly fake the placeholder effect using javascript, but i was hoping for something more simpleSelfreproach
Unfortunately, @amosrivera, there appears to be no standard way: developer.mozilla.org/en/HTML/HTML5/…, other than a scripted workaround.Subject
good solution, but I would add if($(this).val() == 'This is...') to the focus handler, otherwise if you add some text, then lose focus, then click on the textarea again, your text disappears.Angiology
@DenisGolomazov Good addition; I just submitted an edit with the check in the focus handler. I also recommend adding a placeholder class and styling placeholders differently, as shown at this update to my modified jsfiddle example: jsfiddle.net/airandfingers/pdXRx/249Litter
What if the user made input that matches exactly that of placeholder text, won't that will also gets erased ?Fiendish
Any solution for iPad with iOS9?Aholla
For any interested, the only solution I've found with iOS9 is this: codepen.io/kcmr/pen/XJovvQAholla
I know it's a stupid question... But I've spend quite a little time trying to figure out is there any difference between your fiddle and mine. They seem to be the same to me, but while yours works like a charm, mine is not working ;(Villainage
I've found that the issue is due to the change of usage of $.fn.attr('value') from 1.6 to 1.9 (1.9 is the jQuery version I used in my fiddle and that's the reason why the fiddle is not working. I'll figure out from which version the usage exactly changed and update the comment later). Anyway, for jQuery 1.9+, $.fn.val() should be used in this case. Thanks for the great solution.Villainage
@JasonGennaro the link you provided does not contain the placeholder anchor anymore.Coltin
S
461

You can insert a new line html entity &#10; inside the placeholder attribute:

<textarea name="foo" placeholder="hello you&#10;Second line&#10;Third line"></textarea>

Works on: Chrome 62, IE10, Firefox 60

Doesn't work on: Safari 11

https://jsfiddle.net/lu1s/bxkjLpag/2/

Scyphozoan answered 29/9, 2014 at 18:18 Comment(12)
this does exactly what the original question asked for. why isn't it voted up higher? does it not work in every browser?Inter
@Inter - Indeed it doesn't. I just tried it in FF and it prints out the &#10; literally, without producing a whitespace character. See developer.mozilla.org/en/HTML/HTML5/…Bring
@MerlynMorgan-Graham @Inter you're right. If it's not cross-browser maybe it's not really good to implement this. But for sure you can add a little javascript to replace the &#10; of the placeholder and convert them in \n and pass them to the value attribute of the textarea element. Finally replace the placeholder for an empty string.Scyphozoan
Works on IE10 and Chrome 62.Orme
Works very well in newer versions of FirefoxRoux
Works in Firefox 60.Nomology
I just tried it and it didn't do anything in Chrome- HOWEVER I must point out that I'm trying to add the placeholder via React, which might strip this kind of thing out.Parietal
&#10; is converted to a space in Svelte.Kharif
@Kharif maybe you can try with this other html special entity for line break: &#013;Scyphozoan
Can confirm that @Scyphozoan suggestion works for Svelte as of writingAssembled
This works for me in React as well.Receptionist
yes, long live :)Scyphozoan
U
72

UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.


A Nice Little Hack

It doesn't feel nice, but you can just put the new lines in the html. Like this:

<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
1 Long St
London
Postcode
UK"></textarea>

Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:

http://jsfiddle.net/01taylop/HDfju/

  • It is likely that the indent level of each line will vary depending on the width of your text area.
  • It is important to have resize: none; in the css so that the size of the textarea is fixed (See jsfiddle).

Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!


A Better Solution

Check out the JSFiddle.

  • This solution positions a div behind the textarea.
  • Some javascript is used to change the background colour of the textarea, hiding or revealing the placeholder appropriately.
  • The inputs and placeholders must have the same font sizes, hence the two mixins.
  • The box-sizing and display: block properties on the textarea are important or the div behind it will not be the same size.
  • Setting resize: vertical and a min-height on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize property will cause issues when expanding the textarea horizontally.
  • Just make sure the min-height on the textarea is enough to cover your entire placeholder at its smallest width.**

JSFiddle Screenshot

HTML:

<form>
  <input type='text' placeholder='First Name' />
  <input type='text' placeholder='Last Name' />
  <div class='textarea-placeholder'>
    <textarea></textarea>
    <div>
      First Line
      <br /> Second Line
      <br /> Third Line
    </div>
  </div>
</form>

SCSS:

$input-padding: 4px;

@mixin input-font() {
  font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
  font-size: 12px;
  font-weight: 300;
  line-height: 16px;
}

@mixin placeholder-style() {
  color: #999;
  @include input-font();
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

form {
  width: 250px;
}

input,textarea {
  display: block;
  width: 100%;
  padding: $input-padding;
  border: 1px solid #ccc;
}

input {
  margin-bottom: 10px;
  background-color: #fff;

  @include input-font();
}

textarea {
  min-height: 80px;
  resize: vertical;
  background-color: transparent;
  &.data-edits {
    background-color: #fff;
  }
}

.textarea-placeholder {
  position: relative;
  > div {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: $input-padding;
    background-color: #fff;
    @include placeholder-style();
  }
}

::-webkit-input-placeholder {
  @include placeholder-style();
}
:-moz-placeholder {
  @include placeholder-style();
}
::-moz-placeholder {
  @include placeholder-style();
}
:-ms-input-placeholder {
  @include placeholder-style();
}

Javascript:

$("textarea").on('change keyup paste', function() {
  var length = $(this).val().length;
  if (length > 0) {
    $(this).addClass('data-edits');
  } else {
    $(this).removeClass('data-edits');
  }
});
Unto answered 5/11, 2012 at 11:18 Comment(8)
A very cute hack. This definitely works in Chrome. Can we confirm it functions the same in all other major browsers?Sundberg
I would love someone to test it in IE. I can confirm it works on the most recent versions of Safari and Chrome but definitely not Firefox. I now use text instead of placeholder and have a css class to make the text look like a placeholder. Then a small jQuery function to clear the text when it has focus - or put it back if empty!Unto
Works fine in Chrome and IE 11. But not works at Firefox and Android default browser.Stepdame
Not working on Safari, Firefox, Opera. Works only in Chrome :(Statism
While this seem to work great - it's still considered "invalid" html. Just a heads-up.Yorick
This should be the accepted answer, because the current one may submit the "placeholder" value with the form. Note: the solution under "A Better Solution" works correctly cross browser. The comments saying different must refer to "A Nice Little Hack".Sigmund
I used the second hack, but instead of evaluating the length of the val, used a space (placeHolder=' ') as a placeholder and the :not(:placeholder-shown) atrribute for the other class.Incontrovertible
The ugly newline approach detailed at the top of this answer was the one that worked for me when a Vue bind. Vue for some reason ignored the &#10; route (it put those characters in literally) but does honour the literal line breaks.Gobioid
E
65

Don't think you're allowed to do that: http://www.w3.org/TR/html5/forms.html#the-placeholder-attribute

The relevant content (emphasis mine):

The placeholder attribute represents a short hint (a word or short phrase) intended to aid the user with data entry when the control has no value. A hint could be a sample value or a brief description of the expected format. The attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters.

Ere answered 5/9, 2011 at 20:54 Comment(5)
@Selfreproach Hmm. Well, vendors are allowed to interpret the spec in the fashion they see fit.Ere
im a tool, it looked like a line breaking but in fact it was just the placeholder wrapping around the textarea width..Selfreproach
The answer is correct. but I consider the rule total nonsense. What's the exact argument for "must not contain" LR or CR?Romilly
@Jens-AndréKoch I assume the argument is that a placeholder should be simple; if the value is complex enough to need line-breaks, it should exist as a sibling element, similar to what you see if you activate the "show help" link by this comment editor. A placeholder is not visible once an input contains content, after all...Ere
I would like to remove that old answer of mine but it keeps giving me free points every once in a while. Yet your answer is the proper one.Scyphozoan
S
59

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.

Subject answered 5/9, 2011 at 22:47 Comment(10)
i could certainly fake the placeholder effect using javascript, but i was hoping for something more simpleSelfreproach
Unfortunately, @amosrivera, there appears to be no standard way: developer.mozilla.org/en/HTML/HTML5/…, other than a scripted workaround.Subject
good solution, but I would add if($(this).val() == 'This is...') to the focus handler, otherwise if you add some text, then lose focus, then click on the textarea again, your text disappears.Angiology
@DenisGolomazov Good addition; I just submitted an edit with the check in the focus handler. I also recommend adding a placeholder class and styling placeholders differently, as shown at this update to my modified jsfiddle example: jsfiddle.net/airandfingers/pdXRx/249Litter
What if the user made input that matches exactly that of placeholder text, won't that will also gets erased ?Fiendish
Any solution for iPad with iOS9?Aholla
For any interested, the only solution I've found with iOS9 is this: codepen.io/kcmr/pen/XJovvQAholla
I know it's a stupid question... But I've spend quite a little time trying to figure out is there any difference between your fiddle and mine. They seem to be the same to me, but while yours works like a charm, mine is not working ;(Villainage
I've found that the issue is due to the change of usage of $.fn.attr('value') from 1.6 to 1.9 (1.9 is the jQuery version I used in my fiddle and that's the reason why the fiddle is not working. I'll figure out from which version the usage exactly changed and update the comment later). Anyway, for jQuery 1.9+, $.fn.val() should be used in this case. Thanks for the great solution.Villainage
@JasonGennaro the link you provided does not contain the placeholder anchor anymore.Coltin
A
18

Salaamun Alekum

&#10;

Works For Google Chrome

enter image description here

<textarea placeholder="Enter Choice#1 &#10;Enter Choice#2 &#10;Enter Choice#3"></textarea>

I Tested This On Windows 10.0 (Build 10240) And Google Chrome Version 47.0.2526.80 m

08:43:08 AST 6 Rabi Al-Awwal, 1437 Thursday, 17 December 2015

Thank You

Anility answered 26/11, 2015 at 12:26 Comment(0)
B
15

How about a CSS solution: http://cssdeck.com/labs/07fwgrso

::-webkit-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

::-moz-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}

:-ms-input-placeholder::before {
  content: "FIRST\000ASECOND\000ATHIRD";
}
Beeman answered 31/1, 2014 at 16:33 Comment(2)
This solution does not work in Firefox (tested on 22.0-28.0b9).Lightfoot
@Lightfoot I actually noticed the same. For some reason Firefox doesn't handle this correctly. Actually it doesn't work on IE either ==> unfortunately it's WebKit only.Beeman
S
13

Old answer:

Nope, you can't do that in the placeholder attribute. You can't even html encode newlines like &#13;&#10; in a placeholder.

New answer:

Modern browsers give you several ways to do this. See this JSFiddle:

http://jsfiddle.net/pdXRx/5/

Skill answered 5/9, 2011 at 21:18 Comment(1)
Helpful fiddle! Solution 2 actually works in Safari.Illuse
S
12

Use &#10; in place of \n this will change the line.

Scission answered 2/11, 2016 at 7:21 Comment(0)
N
10

Add only &#10 for breaking line, no need to write any CSS or javascript.

textarea{
    width:300px;
    height:100px;

}
<textarea placeholder='This is a line this &#10should be a new line'></textarea>

<textarea placeholder=' This is a line 

should this be a new line?'></textarea>
Nylons answered 13/8, 2019 at 13:58 Comment(0)
Z
6

Try this:

<textarea
placeholder="Line1&#x0a;&#x09;&#x09;&#x09;Line2"
cols="10"
rows="5"
style="resize:none">
</textarea>

http://jsfiddle.net/vr79B/

Zug answered 23/3, 2014 at 9:57 Comment(1)
This is just tabbing some space after the 1st sentence, and cannot be used on more cols or flexible width.Relish
O
5

You can't do it with pure HTML, but this jQuery plugin will let you: https://github.com/bradjasper/jQuery-Placeholder-Newlines

Orifice answered 13/9, 2012 at 15:56 Comment(1)
Nice, worked for me, I replaced the standard jquery.placeholder by matthias with this one and had to replace these calls: $('input, textarea').placeholder(); with this $('input[placeholder], textarea[placeholder]').placeholder();Attitudinarian
M
5

I liked the work of Jason Gennaro and Denis Golomazov, but I wanted something that would be more globally useful. I have modified the concept so that it can be added to any page without repercussion.

http://jsfiddle.net/pdXRx/297/

<h1>Demo: 5 different textarea placeholder behaviors from a single JS</h1>

<h2>Modified behaviors</h2>

<!-- To get simulated placeholder with New Lines behavior,
     add the placeholdernl attribute -->

<textarea placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address' placeholdernl>    (click me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<h2>Standard behaviors</h2>

<textarea placeholder='Address'>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea>    (delete me to demo)
Johnny S. Fiddle
248 Fake St.
Atlanta, GA 30134</textarea>

<textarea placeholder='Address'></textarea>

The javascript is very simple

<script>
(function($){
var handleFocus = function(){
    var $this = $(this);
    if($this.val() === $this.attr('placeholdernl')){
        $this.attr('value', '');
        $this.css('color', '');
    }
};

var handleBlur = function(){
    var $this = $(this);
    if($this.val() == ''){
        $this.attr('value', $this.attr('placeholdernl'))
        $this.css('color', 'gray');
    }    
};

$('textarea[placeholdernl]').each(function(){
    var $this = $(this),
        value = $this.attr('value'),
        placeholder = $this.attr('placeholder');
    $this.attr('placeholdernl', value ? value : placeholder);
    $this.attr('value', '');
    $this.focus(handleFocus).blur(handleBlur).trigger('blur');
});
})(jQuery);
</script>
Munster answered 10/12, 2013 at 19:48 Comment(0)
K
5

Textarea respects the white-space attribute for the placeholder. https://www.w3schools.com/cssref/pr_text_white-space.asp

Setting it to pre-line solved the problem for me.

textarea {
  white-space: pre-line;
}
<textarea placeholder='This is a line     
should this be a new line'></textarea>
Koroseal answered 11/3, 2019 at 22:16 Comment(0)
B
5

I came here for a multiline placeholder solution, then I realised the accepted solution doesn't work when textarea is inside a formik form.

And the solution, in this case, is template literals. It allows you to specify a multi-line string of text.

    <textarea
        cols={40}
        placeholder={`day 1: Temple visit,&#13;&#10;
        day 2: Jungle barbeque,\n
        day 3: Waterfall visit in the evening,\n
        day 4: Visit UNESCO World Heritage Site,\n
        day 5: Art gallery show,\n
        day 6: Visit grand swimming pool,\n
        day 7: Visit to Blue fort`}
        rows={20}
/>

source

Brice answered 27/9, 2021 at 6:49 Comment(1)
this works for react bootstrap as well. <Form.Control as="textarea" ... />Luciferous
A
4

A slightly improved version of the Jason Gennaro's answer (see code comments):

var placeholder = 'This is a line \nthis should be a new line';
$('textarea').attr('value', placeholder);
$('textarea').focus(function(){
    if($(this).val() == placeholder){
        // reset the value only if it equals the initial one    
        $(this).attr('value', '');
    }
});
$('textarea').blur(function(){
    if($(this).val() == ''){
        $(this).attr('value', placeholder);
    }    
});
// remove the focus, if it is on by default
$('textarea').blur();
Angiology answered 6/8, 2013 at 7:21 Comment(0)
W
3

Subject to the caveat that the premise of the question is inconsistent with W3 specifications, so behaviour cannot be guaranteed, solutions using &x10; work when the <textarea> is to be defined in HTML:

<textarea 
  placeholder="HTML entity works &#10; but unicode entity hard-coded \u000A !">
</textarea>

enter image description here

But if the <textarea> is to be created using JavaScript, then the &#10; entity will be hard-coded in the output. Using the unicode equivalent \u000A, however, does work:

let myArea = document.createElement("textarea");
myArea.placeholder = "Unicode works \u000A But HTML entity hard-coded &#10; !";

enter image description here

Weaken answered 30/9, 2022 at 12:42 Comment(0)
B
2

very simple

  var position = your break position;
    var breakLine = "&#13;&#10;";//in html 
    var output = [value.slice(0, position), breakLine, value.slice(position)].join('');
    return output;

value represent the original string

Birt answered 15/4, 2015 at 7:48 Comment(0)
F
2

HTML

<textarea data-placeholder="1111\n2222"></textarea>

JS

$('textarea[data-placeholder]').each(function(){
    var $this = $(this),
        placeholder = $this.data('placeholder'),
        placeholderSplit = placeholder.split('\\n');
    placeholder = placeholderSplit.join('\n');
    $this.focus(function(){
        var $this = $(this);
        if($this.val() === placeholder){
            $this.val('');
            // $this.removeClass('placeholder');
        }
    }).blur(function(){
        var $this = $(this);
        if($this.val() == '') {
            $this.val(placeholder);
            // $this.addClass('placeholder');
        }
    }).trigger('blur');
});
Finnic answered 8/8, 2016 at 10:4 Comment(0)
L
2

Based on a combination of three different tricks I saw this seems to work in all browsers I've tested it in.

HTML:

<textarea placeholder="Line One&#10;Line Two&#10;&#10;Line Four"></textarea>

JS At bottom of HTML file:

<script>
    
    var textAreas = document.getElementsByTagName('textarea');

    Array.prototype.forEach.call(textAreas, function(elem) {
        elem.placeholder = elem.placeholder.replace(/\u000A/g, 
        '                                                     \
                                                              \
                                                              \
        \n\u2063');
    });

</script>

Note, the extra spaces will cause a clean wrap around but there has to be enough spaces that it will fill the width of the textarea, I placed enough that it's sufficient for my projects but you could be robust and generate them by observing the textarea.width and calculating the proper cardinality.

Leilani answered 8/9, 2020 at 1:48 Comment(0)
N
1

I modified @Richard Bronosky's fiddle like this.

It's better approach to use data-* attribute rather than a custom attribute. I replaced <textarea placeholdernl> to <textarea data-placeholder> and some other styles as well.

edited
Here is the Richard's original answer which contains full code snippet.

Nephrotomy answered 23/7, 2014 at 7:8 Comment(2)
Its better that whenever you include a jsfiddle, explain and paste code here as well, so we have it for further reference and we don't have to rely that content will be in jsfiddle forever.Moynihan
You are right, @avcajaraville. But I didn't include full code snippet since Richard's original answer is on the same topic, and mine is just simple modification. Instead, I pointed his answer.Nephrotomy
V
1

Check out this solution with custom placeholder.

  • You get multiline placeholder that works in all browsers (including Firefox)
  • It is posible to customise placeholder as you want

Demo on fiddle.

$(document).on('input', '#textArea', function () {
	
        if ($('#textArea').val()) {
            $('#placeholderDiv').hide();
        } else {
            $('#placeholderDiv').show();
        }   
});
#textAreaWrap {
    position: relative;
    background-color: white;
}

#textArea {
    position: relative;
    z-index: 1;
    width: 350px;
    height: 100px;
    min-height: 100px;
    padding: 6px 12px;
    resize: vertical;
    background-color: transparent;
    /* When set background-color: transparent - Firefox  displays
    unpleasant textarea border. Set border style to fix it.*/
    border: 1px solid #a5a5a5;
}

#placeholderDiv {
    position: absolute;
    top: 0;
    padding: 6px 13px;
    color: #a5a5a5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="textAreaWrap">
    
<textarea id="textArea"></textarea>

<!-- Check here. If textarea has content -
     set for this div attribute style="display: none;" -->
<div id="placeholderDiv">Multiline textarea<br>
                         placeholder<br>
                         <br>
                         that works in Firefox</div>
    
</div>
Vermination answered 15/10, 2015 at 22:22 Comment(0)
E
1

This issue can be tackled by using the placeholder-shown selector and super imposed backgrounds, if your implementation allows:

textarea:not(:placeholder-shown) {
  background: #fff;
}

div {
  top: 0;
  left: 14px;
  color: rgba(0,0,0,0.4);
  z-index: -1;
  position: absolute;
  line-height: 1.2;
  white-space: pre-wrap;
}

https://codepen.io/franciscoaquino/pen/YzyBPYK

Selector support:

https://caniuse.com/#feat=css-placeholder-shown

Evvie answered 21/5, 2020 at 5:52 Comment(0)
H
0

I don't like hiding the placeholder when you focus the textarea. So I made a constructor function Placeholder that looks exactly like the built-in placeholder and works also in other browsers than Google Chrome. It's very convenient because you can use the Placeholder function as often as you want and it doesn't even need jQuery.

EDIT:

It now also handles special cases, like inserting the placeholder, correctly.

var textarea = document.getElementById("textarea");
new Placeholder(textarea, "Line 1\nLine 2\nLine 3");

function Placeholder(el, placeholder) {
    if (el.value == "" || el.value == placeholder) {
        el.style.color = "gray";
        el.value = placeholder;
        el._plc = true;
        el.className += " unselectable";
    }
    function keyPress(e) {
        window.setTimeout(function() {
            var replaced = reverseStr(el.value).replace(reverseStr(placeholder), "");
            
            if (el.value == "") {
                el.value = placeholder;
                el.style.color = "gray";
                cursorToStart(el);
                el._plc = true;
                el.className += " unselectable";
            } else if (el._plc && el.value.endsWith(placeholder) && replaced !== "") {
                el.value = reverseStr(replaced);
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            } else if (el._plc && el.readOnly) {
                var ch = String.fromCharCode(e.charCode);
                if (e.keyCode == 13) ch = "\n";     // ENTER
                else if (e.charCode == 0) return;   // non-character keys
                
                el.value = ch;
                el.style.color = "black";
                el._plc = false;
                el.readOnly = false;
                el.className = el.className.replace("unselectable", "");
            }
        }, 10);
    }
    el.addEventListener("keypress", keyPress, false);
    el.addEventListener("paste", keyPress, false);
    el.addEventListener("cut", keyPress, false);
    el.addEventListener("mousedown", function() {
        if (el._plc) el.readOnly = true;
    }, false);
    el.addEventListener("mouseup", function() {
        el.readOnly = false;
        if (el._plc) cursorToStart(el);
    }, false);
  
    function cursorToStart(input) {
        if (input.createTextRange) {
            var part = input.createTextRange();
            part.move("character", 0);
            part.select();
        } else if (input.setSelectionRange){
            input.setSelectionRange(0, 0);
        } input.focus();
    }
    function reverseStr(str) {
        if (!str) return "";
        return str.split("").reverse().join("");
    }
}
textarea {
    border: 1px solid gray;
    padding: 3px 6px;
    font-family: Arial;
    font-size: 13px;
    transition: .2s;
}
textarea:hover, textarea:focus {
    border-color: #2277cc;
}
textarea:focus {
    box-shadow: inset 0 0 5px #85B7E9;
}
*.unselectable {
    -webkit-user-select: none;
    -webkit-touch-callout: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -o-user-select: none;
}
<textarea id="textarea"></textarea>
Hengel answered 27/2, 2016 at 12:38 Comment(0)
N
0

If you're using Razor in an ASP.NET project, you can do the below, which is helpful for very long placeholder values:

@{ 
    string strPlaceholder = "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
        + "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
        + "Shipment Id to Update, Container Id to Update, New Tracking Number \r\n"
        + "\r\n"
        + "i.e. to update all containers with shipment Id 5803407, etner like this: \r\n"
        + "5803407, , 1Z20579A0322337062 \r\n"
        + "\r\n"
        + "or to update a specific container Id, enter like this: \r\n"
        + "5803407, 112546247, 1Z20579A0322337062 \r\n"
        ;
}
<textarea type="text" class="form-control" style="height:650px;" id="ShipmentList" name="ShipmentList" 
            placeholder="@strPlaceholder" required></textarea>

enter image description here

Normand answered 23/6, 2021 at 21:31 Comment(0)
A
0

In php works fine backslash + r (\r):

<textarea placeholder='This is a line \r this should be a new line'></textarea>
Allhallowmas answered 20/9, 2022 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.