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

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

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.

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
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.

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>

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.

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:

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

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>

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

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, This is multiligne example Have Fun "
rows="5" cols="35"></textarea>

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

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>

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

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.

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

Related

Ho to hide the " | " cursor symbol on click of the input box in IE? [duplicate]

I have a simple input field:
<input id="myInput" class="someClass"></input>
and some JQuery code:
$(e.currentTarget).prop('readonly', true);
where e.currentTargetis that [object HTMLInputElement] as IE11 names it.
I'm only trying to set this input field to be readonly. In chrome that code works but in IE not.
I tried already:
.prop('readonly','readonly');
.prop('readonly', '');
.attr('readonly', true);
but none of them works in IE11 ( in chrome everyone of them works)
Okay, this is bizarre: If you make the field read-only while it has focus, IE11 seems to go a bit bonkers, and one of the ways it goes bonkers is to let you keep modifying the field while the cursor is there — with some keystrokes, but not others. Here's an example: Fiddle
$("#myInput").one("click", function(e) {
$(e.currentTarget).prop('readonly', true);
display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
$("#myInput").on("keydown", function(e) {
display("e.currentTarget.readOnly: " + e.currentTarget.readOnly);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
Adding this line before setting readOnly fixes it (fiddle):
$(e.currentTarget).blur();
Side note: You don't need jQuery to set the readOnly property, just:
e.currentTarget.readOnly = true; // Note the capital O
'Read-only' input element doesn't work consistently in IE 8,9, 10 or 11.
In this case, we can use onkeydown="javascript: return false;" in the input element.
I have used Focusin() function in jquery side with Id. When I click on textbox then we remove readony attribute as below:
HTML:
<input type="text" id="txtCustomerSearch" readonly class="customer-search"
placeholder="Search customer:" maxlength="100" autocomplete="off">
Jquery:
$("#txtCustomerSearch").focusin(function () {
$(this).removeAttr('readonly');
});
Note: it will working in IE11 and other browser.

angular ngModel style

Is it possible to style the value in the attribute ngModel of an input tag?
Example:
<input class="input" type="text" [(ngModel)] = "myService.text">
Let's say the value of text is '28 packages', can I put 28 in bold?
So if i understand correctly you want to have it bold whenever the value is 28 ?
yes its possible you can use a ng-class with a ternary expression like this
.bold{
font-weight:600;
}
<input type="text" ng-class="myService.text == '28 ? 'bold' : '''" class="input" ng-model="myService.text" />
This is not angular-related rather a CSS related question.
You cannot style only a part of an input in HTML/CSS so you won't be able to do it in angular.
Instead, you can use an input that is hidden behind a div. The idea is that when the user clicks the div, you actually focus the input. When the user types text, you capture the content of the input and fill the div with it, eventually adding <span class"highlight"> around the number of packages.
I prepared you a stackblitz in pure CSS/JS. You can adapt it in angular if you want.
Relevant pieces of code :
HTML :
<span id="hiddenSpan">This is the hidden div. Click it and start typing</span>
<div>
<label for="in">The real input</label>
<input id="in" type="text">
</div>
JS :
const input = document.getElementById('in')
const hiddenSpan = document.getElementById('hiddenSpan')
function onInputChanged() {
let text = input.value
const regex = new RegExp('(\\d+) packages')
let result = regex.exec(text)
if(result) {
hiddenSpan.innerHTML = '<span class="highlight">'+result[1]+'</span> packages'
} else {
hiddenSpan.innerHTML = text
}
}
// Capture keystrokes.
input.addEventListener('keyup', onInputChanged)
// Focus the input when the user clicks the pink div.
hiddenSpan.addEventListener('click', function() {
input.focus()
})
CSS :
#hiddenSpan {
background-color: pink;
}
.highlight {
font-weight: bold;
background-color: greenyellow;
}
Note : the downside is that the blinking caret is not visible anymore. You can take a look at this resource if you want to simulate one.
It is not possible to style certain parts of a text <input> field in bold. However, you can use a contenteditable div instead of a text <input> field. Inside the contenteditable div you can have other HTML tags like <strong> to style certain parts of the text however you like.
I created an Angular directive called contenteditableModel (check out the StackBlitz demo here) and you can use it to perform 2-way binding on a contenteditable element like this:
<div class="input" contenteditable [(contenteditableModel)]="myService.text"></div>
The directive uses regular expressions to automatically check for numbers in the inputted text, and surrounds them in a <strong> tag to make them bold. For example, if you input "28 packages", the innerHTML of the div will be formatted like this (to make "28" bolded):
<strong>28</strong> packages
This is the code used in the directive to perform the formatting:
var inputElement = this.elementRef.nativeElement;
inputElement.innerHTML = inputElement.textContent.replace(/(\d+)/g, "<strong>$1</strong>");
this.change.emit(inputElement.textContent);
You can change the <strong> tag to something else (e.g. <span style="text-decoration: underline"> if you want the text to be underlined instead of bolded).
When performing the formatting, there is an issue where the user's text cursor position will be unexpectedly reset back to the beginning of the contenteditable div. To fix this, I used 2 functions (getOriginalCaretPosition and restoreCaretPosition) to store the user's original cursor position and then restore the position back after the text formatting is performed. These 2 functions are kind of complex and they're not entirely relevant to the OP's question so I will not go into much detail about them here. You can PM me if you want to learn more about them.

How to disable autocomplete for all major browsers

How do you disable Autocomplete in the major browsers for a specific input and/or the complete form.
I found this solution:
<input type="text" name="foo" autocomplete="off" />
However, this does not seem to work in all browsers. I've had problems in firefox for instance.
Edit:
My firefox issue has been resolved. That leaves the following: Can I disable autocomplete on a form or do I have to give every input autocomplete="off"
Autocomplete should work with the following <input> types: text, search, url, tel, email, password, datepickers, range, and color.
But alas, you could try adding autocomplete='off' to your <form> tag instead of the <input> tag, unless there's something preventing you from doing that.
If that doesn't work, you could also use JavaScript:
if (document.getElementsByTagName) {
var inputElements = document.getElementsByTagName(“input”);
for (i=0; inputElements[i]; i++) {
if (inputElements[i].className && (inputElements[i].className.indexOf(“disableAutoComplete”) != -1)) {
inputElements[i].setAttribute(“autocomplete”,”off”);
}
}
}
Or in jQuery:
$(document).ready(function(){
$(':input').live('focus',function(){
$(this).attr('autocomplete', 'off');
});
});
You could try manually clearing text fields on page load with javascript, for example:
window.onload = function() {
elements = document.getElementsByTagName("input");
for (var i=0; i<elements.length; ++i) {
elements[i].value = "";
}
};
This might not work if it's executed before the autofill. Another option is to generate part of the name attributes for your inputs randomly each time the page is rendered (and strip them out when the server handles the submit), then the browser won't try to autocomplete.
See also Is autocomplete="off" compatible with all modern browsers?
I found this one. It hides on chrome, edge and opera
<form autocomplete="off">
<input role="presentation" />
</form>
IE: autocomplete
Firefox, Chrome, Opera: disableautocomplete
<input type="text" autocomplete="off" disableautocomplete id="number"/>

Define maxlength for an html textarea

I currently try to restrict the the maximal amount of characters allowed in a textarea.
With:
<textarea rows="4" cols="50" maxlength="50">
It works like it should in Firefox, however there seems to be no effect in IE which poses a problem since quite a lot of the website-users still use IE.
Do you have any suggestions or a workaround?
You can use Javascript to implement maxlength in Internet Explorer.
<textarea rows="4" cols="50" maxlength="50" onKeyPress="return(this.value.length < 50);">
I am suggesting this since you had placed php in the tags, you can truncate the input from the server side using substr
$trunc = substr($_POST['textareaname'], 0, 50);
alternatively you can also use Javascript function.
UPDATE to your comment on how to provide a feedback to the user when limit is reached.
$("#element").keypress(function (e) {
var str = $(this).val();
if (str.length > 100) {
e.preventDefault();
alert('You have reached max limit');
return false;
}
});

How do I get placeholder text in firefox and other browsers that don't support the html5 tag option?

This works in Chrome and any other browser that supports placeholder text in HTML5
<input id="name" name="name" type="text" placeholder="Please enter your name..." required /> <br />
But, it doesn't work in 3.5 and earlier of Firefox, and obviously IE8, and possibly other browsers.
How do I achieve the same thing (preferably in HTML/CSS - if not I am open to suggestions), to support all the older browsers? If not every single browser, at least Firefox and IE.
Safari and Chrome already support it (or the latest versions anyway).
Thanks.
One day I'll get around to properly documenting this, but see this example: http://dorward.me.uk/tmp/label-work/example.html
In short — position a <label> under a transparent <input> using <div> to provide background colour and borders.
Then use JS to determine if the label should be visible or not based on focusing.
Apply different styles when JS is not available to position the label beside the element instead.
Unlike using the value, this doesn't render the content inaccessible to devices which only display the focused content (e.g. screen readers), and also works for inputs of the password type.
I use this one: https://github.com/danbentley/placeholder
Lightweight and simple jQuery plugin.
Here is the simplest solution that I found working everywhere:
<input id="search"
name="search"
onblur="if (this.value == '') {this.value = 'PLACEHOLDER';}"
onfocus="if (this.value == 'PLACEHOLDER') {this.value = '';}"
/>
Replace PLACEHOLDER with your own.
At the moment, FF3 does not yet support the "placeholder" attribute of the "input" element. FF4, Opera11 and Chrome8 support it partially, i.e. they render the placeholder text in the field, but do not delete it when the user focuses in the field, which is worse that not supporting it at all.
I use the following snippet that I wrote with jQuery. Just add a class of textbox-auto-clear to any textbox on the page and you should be good to go.
<input type="text" value="Please enter your name" class="textbox-auto-clear" />
$(".textbox-auto-clear").each(function(){
var origValue = $(this).val(); // Store the original value
$(this).focus(function(){
if($(this).val() == origValue) {
$(this).val('');
}
});
$(this).blur(function(){
if($(this).val() == '') {
$(this).val(origValue);
}
});
});
I assume that you want to keep using the placeholder attribute for HTML5 browsers, in which case you'd have to do some browser detection and only apply the jQuery solution to browsers that don't support it.
Better yet, you can us the Modernizer library, as outlined in this answer.
Detecting support for specific HTML 5 features via jQuery
Here is a MooTools Plugin, that brings the placeholder to browsers that don't support it yet:
http://mootools.net/forge/p/form_placeholder
I use this one: https://github.com/Jayphen/placeholder
This lightweight and simple jQuery plugin is a fork of danbentley/placeholder.
Advantage: it adds a class "placeholder" to input fields that are temporarily filled.
Css ".placeholder {color:silver}" make the polyfill text look like a placeholder instead of regular input text.
Disadvantage: It doesn't polyfill the placeholder of a password field.
By the way...if anyone is interested...I found a nice elegant solution that is a jQuery plugin that is SOOO nice.
It literally is one line of jQuery, a minified js plugin, along with a simple class name on the input.
http://labs.thesedays.com/projects/jquery/clearfield/
It's the most beautiful thing I have discovered, next to 'Placeholder' in html.
The trick is to use javascript functions onBlur() and onFocus().
Here is the code that worked for me:
<script language="javascript" type="text/javascript" >
var hint_color = "grey", field_color = null;
var hinted = true;
function hint() { // set the default text
document.getElementById('mce-EMAIL').style.color = hint_color;
document.getElementById('mce-EMAIL').value = "<?php echo SUBSCRIPTION_HINT; ?>";
hinted = true;
}
function hintIfEmpty() { // set the default text, only if the field is empty
if (document.getElementById('mce-EMAIL').value == '') hint();
}
function removeHint() {
if (hinted) {
document.getElementById('mce-EMAIL').style.color = field_color;
document.getElementById('mce-EMAIL').value = "";
hinted = false;
}
}
function send() {
document.getElementById('subscription_form').submit();
hint();
}
</script>
<div style="position:absolute; display: block; top:10; left:10; ">
<form id="subscription_form" action="<?php echo SUBSCRIPTION_LINK; ?>" method="post" target="_blank">
<input type="email" value="" name="EMAIL" class="email" id="mce-EMAIL" style="width: 122px;" onBlur="hintIfEmpty();" onFocus="removeHint();" required>
<font style="position: relative; top:-1px;"><b>ok</b></font>
</form>
</div>
<script language="javascript" type="text/javascript" >
field_color = document.getElementById('mce-EMAIL').style.color;
hint();
</script>
SUBSCRIPTION_HINT (i.e.: "your e-mail" ) and SUBSCRIPTION_LINK (i.e.: the value of the 'action' tag in your EN mailchimp embed code...) are PHP constants used for localization.
For "placeholder" work in Firefox just add the attribute
::-moz-placeholder
in CSS tags.
Works for me, change your CSS to
::-webkit-input-placeholder {
color: #999;
}