restrict breaks or excessive spaces in text area? - html

Can someone please help me, i have a text area and i have limited the number of characters in it so that the text area fits the content in it without the content overflowing.
Character length works but this doesn't stop the user currently using the space bar to create breaks or excessive spacing, i.e. more than one space. is there a way i can make the text area stop users spacing characters more than once and forbid line breaks?
Sorry if this is a really obvious question but im looking for an answer everywhere and cant find one anywhere.
<form action="includes/change_status.php" id="form2" method="post" name="form2">
<div class="status-border-top"></div>
<div class="status-border">
<textarea data-id="status" id="status" maxlength="80" name="status" style="width: 187px; margin-top:-4px; text-align:left; padding-left:5px; padding-top:3px; padding-bottom:2px; padding-right:3px; margin-left:-4px; height: 54px; font-size:12px; resize: none; border: hidden; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; position:relative; z-index:100;"><?php echo htmlspecialchars ($profile['status']); ?></textarea>
<input class="status-submit" id="submit" name="submit" src="../PTB1/assets/img/icons/save-status.png" type="image" value="submit">
</div>
</form>

This is how you can remove double spaces or line breaks that the user enters into the textarea.
You'll need to use the latest version of jQuery for this to work.
Working example on jsFiddle.
HTML:
<form action="/" method="post">
<textarea cols="33" rows="12" id="message"></textarea>
</form>
JavaScript:
var $message = $("#message");
$message.on("keydown keypress", function() {
var $this = $(this),
val = $(this).val()
.replace(/(\r\n|\n|\r)/gm," ") // replace line breaks with a space
.replace(/ +(?= )/g,''); // replace extra spaces with a single space
$this.val(val);
});

Another option without jQuery is to compare the currently assigned key to the previous key. If they are the same, and both are in the set of illegal keys, refuse the keypress action. This approach will not change the starting text in any way, no matter what spacing that has.
HTML:
<form action="includes/change_status.php" id="form2" method="post" name="form2">
<div class="status-border-top"></div>
<div class="status-border">
<!-- notice the onkeypress attribute -->
<textarea data-id="status" id="status" maxlength="80" name="status" style="width: 187px; margin-top:-4px; text-align:left; padding-left:5px; padding-top:3px; padding-bottom:2px; padding-right:3px; margin-left:-4px; height: 54px; font-size:12px; resize: none; border: hidden; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; position:relative; z-index:100;" onkeypress="return ignoreSpaces(event);"><?php echo htmlspecialchars ($profile['status']); ?></textarea>
<input class="status-submit" id="submit" name="submit" src="../PTB1/assets/img/icons/save-status.png" type="image" value="submit">
</div>
</form>
Javascript:
var lastkey;
var ignoreChars = ' \r\n'+String.fromCharCode(0);
function ignoreSpaces(e){
e = e || window.event;
var char = String.fromCharCode(e.charCode);
if(ignoreChars.indexOf(char) >= 0 && ignoreChars.indexOf(lastkey) >= 0){
lastkey = char;
return false;
}else{
lastkey = char;
return true;
}
}
working JFiddle: http://jsfiddle.net/mLYgD/1/

Without client-side scripting, you cannot impose such restrictions.
Since you want to allow at most 80 characters and to disallow line breaks, it would seem to be more adequate to use an input type=text element than a textarea.
Moreover, for input type=text, you can impose restrictions using the HTML5 pattern attribute. Though not supported by old browsers, it works in modern browsers even when client-side scripting has been disabled. You could use code like this:
<input type="text" data-id="status" id="status" maxlength="80" size="80"
name="status" pattern="\s?(\S+\s?)*">
The size attribute specifies the visible width of the field in (average-width) characters. The default font face and font size in an input box depends on the browser, but usually the face is not monospace, unlike in textarea. So if monospace font is desired, set it in CSS.
The value of the pattern attribute has the same syntax as JavaScript regular expressions, except that the match is for the entire input string (so a leading ^ and a trailing $ are implied). The notation \s means any whitespace character (in this context, this means a space in practice), and \S means any non-whitespace character, so the expression allows spaces but not in succession. The leading part \s allows a single leading space; remove it if you don’t want to allow that.
You can use JavaScript to implement the pattern attribute in browsers that do not natively support the attribute but have scripting enabled. Or you can just have JavaScript that uses the same expression (with ^ and $ added).

Related

Form input size

How do I change the input box so it makes a new line after a certain length and also so that it adjusts its size too in react js
<form>
<input
className="form message"
onBlur={handleBlur}
placeholder="MESSAGE"
onChange={handleChange}
name="message"
value={values.message}
/>
</form>
For multiline inputs, you should use texteareas. If you want to dynamically change its height, maybe you could just increment the rows attribute depending on your content length.
You should be using a <textarea>. In practice, <input> fields should only be one line.
You do not need React to modify the height of a textarea. You can do it pretty easily below:
function updateHeight(element) {
element.style.height = "1px";
element.style.height = (element.scrollHeight)+"px";
}
textarea{
width:90%;
margin:auto;
}
<textarea oninput="updateHeight(this)" style="overflow:hidden; height:19px"></textarea>

Can CSS be used for putting commas in input fields? [duplicate]

Is it possible to format numbers with CSS?
That is: decimal places, decimal separator, thousands separator, etc.
The CSS working group has publish a Draft on Content Formatting in 2008.
But nothing new right now.
Unfortunately, it's not possible with CSS currently, but you can use Number.prototype.toLocaleString(). It can also format for other number formats, e.g. latin, arabic, etc.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
Well, for any numbers in Javascript I use next one:
var a = "1222333444555666777888999";
a = a.replace(new RegExp("^(\\d{" + (a.length%3?a.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();
and if you need to use any other separator as comma for example:
var sep = ",";
a = a.replace(/\s/g, sep);
or as a function:
function numberFormat(_number, _sep) {
_number = typeof _number != "undefined" && _number > 0 ? _number : "";
_number = _number.replace(new RegExp("^(\\d{" + (_number.length%3? _number.length%3:0) + "})(\\d{3})", "g"), "$1 $2").replace(/(\d{3})+?/gi, "$1 ").trim();
if(typeof _sep != "undefined" && _sep != " ") {
_number = _number.replace(/\s/g, _sep);
}
return _number;
}
Probably the best way to do so is combo of setting a span with a class denoting your formatting then use Jquery .each to do formatting on the spans when the DOM is loaded...
Not an answer, but perhpas of interest. I did send a proposal to the CSS WG a few years ago. However, nothing has happened. If indeed they (and browser vendors) would see this as a genuine developer concern, perhaps the ball could start rolling?
No, you have to use javascript once it's in the DOM or format it via your language server-side (PHP/ruby/python etc.)
If it helps...
I use the PHP function number_format() and the Narrow No-break Space ( ). It is often used as an unambiguous thousands separator.
echo number_format(200000, 0, "", " ");
Because IE8 has some problems to render the Narrow No-break Space, I changed it for a SPAN
echo "<span class='number'>".number_format(200000, 0, "", "<span></span>")."</span>";
.number SPAN{
padding: 0 1px;
}
Another solution with pure CSS+HTML and the pseudo-class :lang().
Use some HTML to mark up the number with the classes thousands-separator and decimal-separator:
<html lang="es">
Spanish: 1<span class="thousands-separator">200</span><span class="thousands-separator">000</span><span class="decimal-separator">.</span>50
</html>
Use the lang pseudo-class to format the number.
/* Spanish */
.thousands-separator:lang(es):before{
content: ".";
}
.decimal-separator:lang(es){
visibility: hidden;
position: relative;
}
.decimal-separator:lang(es):before{
position: absolute;
visibility: visible;
content: ",";
}
/* English and Mexican Spanish */
.thousands-separator:lang(en):before, .thousands-separator:lang(es-MX):before{
content: ",";
}
Codepen:
https://codepen.io/danielblazquez/pen/qBqVjGy
I don't think you can. You could use number_format() if you're coding in PHP. And other programing languages have a function for formatting numbers too.
You cannot use CSS for this purpose. I recommend using JavaScript if it's applicable. Take a look at this for more information: JavaScript equivalent to printf/string.format
Also As Petr mentioned you can handle it on server-side but it's totally depends on your scenario.
You could use Jstl tag Library for formatting for JSP Pages
JSP Page
//import the jstl lib
<%# taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}"
type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number"
maxFractionDigits="3" value="${balance}" /></p>
<p>Formatted Number (4): <fmt:formatNumber type="number"
groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent"
minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number"
pattern="###.###E0" value="${balance}" /></p>
Result
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3
Another js solution to improve the work of Skeeve:
<input type="text" onkeyup="this.value=this.value.toString().replaceAll(/[^\d]/g, '').replaceAll(/(\d)(?=(?:\d\d\d)+$)/g, '$1\u202f')" pattern="[0-9\s]*">
Example as inline-JavaScript in an input[type=number]-Html field, using Intl vanilla JS:
<input class="form-number"
type="number"
id="bar"
name="foo"
value=""
step="any"
min="0"
size="20"
onfocusout="this.value = (new Intl.NumberFormat('de-DE').format(this.value));">
The closest thing I could find is the <input type="number" /> tag, which does do formatting in plain HTML but is also an input field. To make it look like plain text, you could use a bit of CSS.
Unfortunately I don't know how to fix the right margin without JavaScript or using a monospace font and set the width attribute server side.
HTML:
<p>In <input type="number" value="1.223" readonly="readonly" size="1" /> line</p>
CSS:
p {font-family: verdana;}
input {
font-family: verdana;
font-size: 16px;
}
input[readonly] {
border: 0;
padding: 0;
margin: 0;
min-width: 3em;
font-size: 16px;
}
/* Chrome, Safari, Edge, Opera */
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
/* Firefox */
input[type=number] {
-moz-appearance: textfield;
}
as for thousand separators this is what I found on Wikipedia, in the code of this page. Below is the number 149597870700 with .15em margins as thousand separators:
<span style="white-space:nowrap">
149
<span style="margin-left:.15em;">597</span>
<span style="margin-left:.15em;">870</span>
<span style="margin-left:.15em;">700</span>
</span>

css input text name value color [duplicate]

Is it possible to use a CSS selector to target an input that has a specific value?
Example: How can I target the input below based on the value="United States"
<input type="text" value="United States" />
Dynamic Values (oh no! D;)
As npup explains in his answer, a simple css rule will only target the attribute value which means that this doesn't cover the actual value of the html node.
JAVASCRIPT TO THE RESCUE!
Ugly workaround: http://jsfiddle.net/QmvHL/
Original Answer
Yes it's very possible, using css attribute selectors you can reference input's by their value in this sort of fashion:
input[value="United States"] { color: #F90; }​
• jsFiddle example
from the reference
[att] Match when the element sets the "att" attribute, whatever the
value of the attribute.
[att=val] Match when the element's "att"
attribute value is exactly "val".
[att~=val] Represents an element
with the att attribute whose value is a white space-separated list of
words, one of which is exactly "val". If "val" contains white space,
it will never represent anything (since the words are separated by
spaces). If "val" is the empty string, it will never represent
anything either.
[att|=val] Represents an element with the att
attribute, its value either being exactly "val" or beginning with
"val" immediately followed by "-" (U+002D). This is primarily intended
to allow language subcode matches (e.g., the hreflang attribute on the
a element in HTML) as described in BCP 47 ([BCP47]) or its successor.
For lang (or xml:lang) language subcode matching, please see the :lang
pseudo-class.
css attribute selectors reference
It is possible, if you're using a browser which supports the CSS :valid pseudo-class and the pattern validation attribute on inputs -- which includes most modern browsers except IE9.
For instance, to change the text of an input from black to green when the correct answer is entered:
input {
color: black;
}
input:valid {
color: green;
}
<p>Which country has fifty states?</p>
<input type="text" pattern="^United States$">
Yes, but note: since the attribute selector (of course) targets the element's attribute, not the DOM node's value property (elem.value), it will not update while the form field is being updated.
Otherwise (with some trickery) I think it could have been used to make a CSS-only substitute for the "placeholder" attribute/functionality. Maybe that's what the OP was after? :)
As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:
<style>
input:not([value=""]){
border:2px solid red;
}
</style>
<input type="text" onkeyup="this.setAttribute('value', this.value);"/>
Sure, try:
input[value="United States"]{ color: red; }
jsFiddle example.
You can use Css3 attribute selector or attribute value selector.
/This will make all input whose value is defined to red/
input[value]{
color:red;
}
/This will make conditional selection depending on input value/
input[value="United States"]{
color:red;
}
There are other attribute selector like attribute contains value selector,
input[value="United S"]{
color: red;
}
This will still make any input with United state as red text.
Than we attribute value starts with selector
input[value^='united']{
color: red;
}
Any input text starts with 'united' will have font color red
And the last one is attribute value ends with selector
input[value$='States']{
color:red;
}
Any input value ends with 'States' will have font color red
Refreshing attribute on events is a better approach than scanning value every tenth of a second...
http://jsfiddle.net/yqdcsqzz/3/
inputElement.onchange = function()
{
this.setAttribute('value', this.value);
};
inputElement.onkeyup = function()
{
this.setAttribute('value', this.value);
};
In Chrome 72 (2019-02-09) I've discovered that the :in-range attribute is applied to empty date inputs, for some reason!
So this works for me: (I added the :not([max]):not([min]) selectors to avoid breaking date inputs that do have a range applied to them:
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
Screenshot:
Here's a runnable sample:
window.addEventListener( 'DOMContentLoaded', onLoad );
function onLoad() {
document.getElementById( 'date4' ).value = "2019-02-09";
document.getElementById( 'date5' ).value = null;
}
label {
display: block;
margin: 1em;
}
input[type=date]:not([max]):not([min]):in-range {
color: blue;
}
<label>
<input type="date" id="date1" />
Without HTML value=""
</label>
<label>
<input type="date" id="date2" value="2019-02-09" />
With HTML value=""
</label>
<label>
<input type="date" id="date3" />
Without HTML value="" but modified by user
</label>
<label>
<input type="date" id="date4" />
Without HTML value="" but set by script
</label>
<label>
<input type="date" id="date5" value="2019-02-09" />
With HTML value="" but cleared by script
</label>
Following the currently top voted answer, I've found using a dataset / data attribute works well.
//Javascript
const input1 = document.querySelector("#input1");
input1.value = "0.00";
input1.dataset.value = input1.value;
//dataset.value will set "data-value" on the input1 HTML element
//and will be used by CSS targetting the dataset attribute
document.querySelectorAll("input").forEach((input) => {
input.addEventListener("input", function() {
this.dataset.value = this.value;
console.log(this);
})
})
/*CSS*/
input[data-value="0.00"] {
color: red;
}
<!--HTML-->
<div>
<p>Input1 is programmatically set by JavaScript:</p>
<label for="input1">Input 1:</label>
<input id="input1" value="undefined" data-value="undefined">
</div>
<br>
<div>
<p>Try typing 0.00 inside input2:</p>
<label for="input2">Input 2:</label>
<input id="input2" value="undefined" data-value="undefined">
</div>

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

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