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

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>

Related

Format Interactive Placeholder Text in HTML Input Date via CSS [duplicate]

By default, the input type="date" shows date as YYYY-MM-DD.
The question is, is it possible to force it's format to something like: DD-MM-YYYY?
It is impossible to change the format
We have to differentiate between the over the wire format and the browser's presentation format.
Wire format
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Presentation format
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us will be shown 01/30/2019 instead of the format they are accustomed to: 30-01-2019.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.
Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.
The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.
You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)
Standards-compliant, no hacks.
Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It's 2018, so chances are it'll surely cover most of your users.
Hope it helps!
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn't check for others, but don't expect to fail on any Webkit.
It's important to distinguish two different formats:
The RFC 3339/ISO 8601 "wire format": YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input's value upon form submission or when requested via the DOM API. It is locale and region independent.
The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user's preferences selection. For example, on Mac OS with the region "United States" selected in the Language & Text preferences pane, Chrome 20 uses the format "m/d/yy".
The HTML5 specification does not include any means of overriding or manually specifying either format.
I found a way to change format, it's a tricky way, I just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
input[type="date"]::-webkit-datetime-edit-year-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 56px;
}
input[type="date"]::-webkit-datetime-edit-month-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 26px;
}
input[type="date"]::-webkit-datetime-edit-day-field{
position: absolute !important;
color:#000;
padding: 2px;
left: 4px;
}
<input type="date" value="2019-12-07">
I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.
Google Chrome in its last beta version finally uses the input type=date, and the format is DD-MM-YYYY.
So there must be a way to force a specific format. I'm developing a HTML5 web page and the date searches now fail with different formats.
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don't waste your time trying to handle this with pure JavaScript. I wasted my time trying to make it dd/mm/yyyy. There's no complete solutions that fits with all browsers. So I recommend to use momentJS / jQuery datepicker or tell your client to work with the default date format instead
Browsers obtain the date-input format from user's system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, it~s not possible to implement the same in browsers.
Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system's setting. Web authors have no way to change the date format because there currently is no standards to specify the format.
So no need to change it, if we don't change anything, users will see the date-input's format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.
To change the format in Chrome (e.g. from US "MM/DD/YYYY" to "DD/MM/YYYY") you go to >Settings >Advanced >Add language (choose English UK). Then:
The browser gets restarted and you will find date input fields like this: ´25/01/2022
Refer google developers page on same.
WHATWG git hub query on same
Test using below date input:
<input type="date" id="dob" value=""/>
Try this if you need a quick solution To make yyyy-mm-dd go "dd- Sep -2016"
1) Create near your input one span class (act as label)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
As said, the <input type=date ... > is not fully implemented in most browsers, so let's talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG, LC_TIME don't seems to work(for me at least).
You can type locale in a terminal to see your current values. I think the same concept can be applied to IOS.
eg:
Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is:
https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/
and
https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date:
$ date +%x
01-06-2015
But as LC_TIME and d_fmt seems to be rejected by chrome ( and I think it's a bug in webkit or chrome ), sadly it don't work. :'(
So, unfortunately the response, is IF LANG environment variable do not solve your problem, there is no way yet.
It's not possible to change web-kit browsers use user's computer or mobiles default date format.
But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants.
the link to the jquery UI date-picker is
on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can't force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do.
E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
it splits the date which i get as dd/mm/yyyy (using split()) on basis of "/" and makes an array,
it then reverse the array (using reverse()) since the date input supports the reverse
of what i get.
then it joins (using join())the array to a string according the
format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
I adjusted the code from Miguel to make it easier to understand
and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
NEW in Firefox (since unknown version), in Settings > Language, they have added an option: Use your operating system settings for “Spanish (Spain)” to format dates, times, numbers, and measurements
This option will use the Operating System's locale to display dates! Too bad it does not come enabled by default (maybe from a fresh install it does?)
Angular devs (and maybe others) could consider this partial solution.
My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.
It's not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It's not going to be very helpful if you have just one date input.
<input class="form-control"
[type]="myInputFocus ? 'date' : 'text'"
id="myInput"
name="myInput"
#myInput="ngModel"
[(ngModel)]="myDate"
(focus)="myInputFocus = true"
(blur)="myInputFocus = false">
And simply declare myInputFocus = false at the beginning of you component class.
Obviously point myDate to your desired control.
Thanks to #safi eddine and #Hezbullah Shah
Datepicker with VanillaJS and CSS.
CSS - STYLE:
/*================== || Date Picker ||=======================================================================================*/
/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
color: transparent;
}
/*------- DatePicker ------------------------*/
input[type="date"] {
background-color: aqua;
border-radius: 4px;
border: 1px solid #8c8c8c;
font-weight: 900;
}
/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus
{
outline: none;
box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
/*------- Year ------------------------*/
input[type="date"]::-webkit-datetime-edit-year-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 56px;
}
/*------- Month ------------------------*/
input[type="date"]::-webkit-datetime-edit-month-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 26px;
}
/*------- Day ------------------------*/
input[type="date"]::-webkit-datetime-edit-day-field {
position: absolute !important;
color: #000;
padding: 2px;
left: 4px;
}
JAVASCRIPT:
// ================================ || Format Date Picker || ===========================================================
function GetFormatedDate(datePickerID)
{
let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
return rawDate.split('-').reverse().join("-"); // Reverse the date
}
USING:
document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID
const birthday = document.getElementById("birthday");
const button = document.getElementById("wishBtn");
button.addEventListener("click", () => {
let dateValue = birthday.value;
// Changing format :)
dateValue = dateValue.split('-').reverse().join('-');
alert(`Happy birthday king/Queen of ${dateValue}`);
});
<input type="date" id="birthday" name="birthday" value="2022-10-10"/>
<button id="wishBtn">Clik Me</button>
Not really no.
Hackable but very slim & customizable solution would be to:
Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
Put a text input on top of it
On text input click, use JS to get date input element & call .showPicker()
store date picker value elsewhere
show value in your custom format you want in the text input
Here's some sample react code:
<div style={{ width: "100%", position: "relative" }}>
<input type="date" className={`form-control ${props.filters[dateFromAccessor] ? '' : 'bh-hasNoValue'}`} id={`${accessor}-date-from`} placeholder='from'
value={toDate(props.filters[dateFromAccessor])} style={{ marginRight: 0, visibility: "hidden" }}
onChange={e => {
props.setFilters({ ...props.filters, [dateFromAccessor]: inputsValueToNumber(e) })
}} />
<input type="text" className="form-control" readOnly
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", backgroundColor: "white" }}
value={toDate(props.filters[dateFromAccessor])}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
(document.getElementById(`${accessor}-date-from`) as any)?.showPicker();
}}></input>
</div>
I know it's an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.

Not showing placeholder for input type="date" field

I am doing a phonegap app. When I am trying type="date" input field as shown below, it shows date picker in iPhone as I expected but it doesn't show the placeholder I have given. I found the same issue here in SO, but no solution anywhere.
<input placeholder="Date" class="textbox-n" type="date" id="date">
It may not be appropriate... but it helped me.
What I did is start with a text input field, then change the type to a date input when the input is in focus.
<input
placeholder="Date"
class="textbox-n"
type="text"
onfocus="(this.type='date')"
id="date" />
If you use mvp's method but add the onblur event to change it back to a text field so the placeholder text appears again when the input field looses focus. It just makes the hack a little bit nicer.
<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date" />
I ended up using the following.
Regarding Firefox comment(s): Generally, Firefox will not show any text placeholder for inputs type date.
But as this is a Cordova/PhoneGap question this should be of no concern (Unless you want to develop against FirefoxOS).
input[type="date"]:not(.has-value):before{
color: lightgray;
content: attr(placeholder);
}
<input type="date" placeholder="MY PLACEHOLDER" onchange="this.className=(this.value!=''?'has-value':'')">
As of today (2016), I have successfully used those 2 snippets (plus they work great with Bootstrap4).
Input data on the left, placeholder on the left
input[type=date] {
text-align: right;
}
input[type="date"]:before {
color: lightgrey;
content: attr(placeholder) !important;
margin-right: 0.5em;
}
Placeholder disappear when clicking
input[type="date"]:before {
color: lightgrey;
content: attr(placeholder) !important;
margin-right: 0.5em;
}
input[type="date"]:focus:before {
content: '' !important;
}
I used this in my css:
input[type="date"]:before{
color:lightgray;
content:attr(placeholder);
}
input[type="date"].full:before {
color:black;
content:""!important;
}
and put somenthing like this into javascript:
$("#myel").on("input",function(){
if($(this).val().length>0){
$(this).addClass("full");
}
else{
$(this).removeClass("full");
}
});
it works for me for mobile devices (Ios8 and android). But I used jquery inputmask for desktop with input text type. This solution it's a nice way if your code run on ie8.
Based on deadproxor and Alessio answers, I would try only using CSS:
input[type="date"]::before{
color: #999;
content: attr(placeholder) ": ";
}
input[type="date"]:focus::before {
content: "" !important;
}
And if you need to make the placeholder invisible after writing something in the input, we could try using the :valid and :invalid selectors, if your input is a required one.
EDIT
Here the code if you are using required in your input:
input[type="date"]::before {
color: #999999;
content: attr(placeholder);
}
input[type="date"] {
color: #ffffff;
}
input[type="date"]:focus,
input[type="date"]:valid {
color: #666666;
}
input[type="date"]:focus::before,
input[type="date"]:valid::before {
content: "" !important;
}
<input type="date" placeholder="Date" required>
I took jbarlow idea, but I added an if in the onblur function so the fields only change its type if the value is empty
<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.value == '' ? this.type='text' : this.type='date')" id="date">
According to the HTML standard:
The following content attributes must not be specified and do not apply to the element: accept, alt, checked, dirname, formaction, formenctype, formmethod, formnovalidate, formtarget, height, inputmode, maxlength, minlength, multiple, pattern, placeholder, size, src, and width.
It works for me:
input[type='date']:after {
content: attr(placeholder)
}
I used this whit jQuery:
http://jsfiddle.net/daviderussoabram/65w1qhLz/
$('input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="month"], input[type="time"], input[type="week"]').each(function() {
var el = this, type = $(el).attr('type');
if ($(el).val() == '') $(el).attr('type', 'text');
$(el).focus(function() {
$(el).attr('type', type);
el.click();
});
$(el).blur(function() {
if ($(el).val() == '') $(el).attr('type', 'text');
});
});
Found a better way to solve your problem.
I think this will help you. when focused out, the box will change type into text so it will show your placeholder. when focused in, its type changes into date so the calendar view will be shown.
<input placeholder="Date" class="textbox-n" type="text" onfocusin="(this.type='date')" onfocusout="(this.type='text')" id="date">
<input placeholder="01-01-2021" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date" />
Adressing the problem in the current correct answer "clicking the field shows the onscreen keyboard instead of the datepicker":
The problem is caused by the Browser behaving according to the type of input when clicking (=text). Therefore it is necessary to stop from focussing on the input element (blur) and then restart focus programmatically on the input element which was defined as type=date by JS in the first step. Keyboard displays in phonenumber-mode.
<input placeholder="Date" type="text" onfocus="this.type='date';
this.setAttribute('onfocus','');this.blur();this.focus();">
To summarize the date inputs problem:
You have to display them (i.e. avoid display:none) otherwise the input UI will not be triggered ;
a placeholder is contradictory with them (as per the spec, and because they have to display a specific UI) ;
converting them to another input type for the unfocused time do allows placeholders, but focus then triggers the wrong input UI (keyboard), at least for a small time, because focus events cannot be cancelled.
inserting (before) or adding (after) content doesn't prevent the date input value to be displayed.
The solution I found to meet those requirements is to use the usual trick to style native form elements : ensure the element is displayed but not visible, and display its expected style through its associated label. Typically, the label will display as the input (including a placeholder), but over it.
So, an HTML like:
<div class="date-input>
<input id="myInput" type="date">
<label for="myInput">
<span class="place-holder">Enter a date</span>
</label>
</div>
Could be styled as:
.date-input {
display: inline-block;
position: relative;
}
/* Fields overriding */
input[type=date] + label {
position: absolute; /* Same origin as the input, to display over it */
background: white; /* Opaque background to hide the input behind */
left: 0; /* Start at same x coordinate */
}
/* Common input styling */
input[type=date], label {
/* Must share same size to display properly (focus, etc.) */
width: 15em;
height: 1em;
font-size: 1em;
}
Any event (click, focus) on such an associated label will be reflected on the field itself, and so trigger the date input UI.
Should you want to test such a solution live, you can run this Angular version from your tablet or mobile.
try my solution. I use 'required' attribute to get know whether input is filled and if not I show the text from attribute 'placeholder'
//HTML
<input required placeholder="Date" class="textbox-n" type="date" id="date">
//CSS
input[type="date"]:not(:valid):before {
content: attr(placeholder);
// style it like it real placeholder
}
Took me a while figuring this one out, leave it as type="text", and add onfocus="(this.type='date')", just as shown above.
I even like the onBlur idea mentioned above
<input placeholder="Date" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date">
Hope this helps anyone who didn't quite gather whats going on above
SO what i have decided to do finally is here and its working fine on all mobile browsers including iPhones and Androids.
$(document).ready(function(){
$('input[type="date"]').each(function(e) {
var $el = $(this),
$this_placeholder = $(this).closest('label').find('.custom-placeholder');
$el.on('change',function(){
if($el.val()){
$this_placeholder.text('');
}else {
$this_placeholder.text($el.attr('placeholder'));
}
});
});
});
label {
position: relative;
}
.custom-placeholder {
#font > .proxima-nova-light(26px,40px);
position: absolute;
top: 0;
left: 0;
z-index: 10;
color: #999;
}
<label>
<input type="date" placeholder="Date">
<span class="custom-placeholder">Date</span>
</label>
Date
Im working with ionicframework and solution provided by #Mumthezir is almost perfect. In case if somebody would have same problem as me(after change, input is still focused and when scrolling, value simply dissapears) So I added onchange to make input.blur()
<input placeholder="Date" class="textbox-n" type="text" onfocus=" (this.type='date')" onchange="this.blur();" id="date">
You can
set it as type text
convert to date on focus
make click on it
...let user check date
on change store the value
set input to type text
set text type input value to the stored value
like this...
$("#dateplaceholder").change(function(evt) {
var date = new Date($("#dateplaceholder").val());
$("#dateplaceholder").attr("type", "text");
$("#dateplaceholder").val(date.getDate() + "/" + (date.getMonth() + 1) + "/" + date.getFullYear());
});
$("#dateplaceholder").focus(function(evt) {
$("#dateplaceholder").attr("type", "date");
setTimeout('$("#dateplaceholder").click();', 500);
});
$("#dateplaceholder").attr("type", "text");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="date" id="dateplaceholder" placeholder="Set the date" />
Found a better way to handle user basic comprehension with mouseover and opening datepicker on click :
<input type="text" onfocus="(this.type='date')" onmouseover="(this.type = 'date')" onblur="(this.value ? this.type = 'date' : this.type = 'text')" id="date_start" placeholder="Date">
Also hide webkit arrow and make it 100% wide to cover the click :
input[type="date"] {
position: relative;
}
input[type="date"]::-webkit-calendar-picker-indicator {
position: absolute;
height: 100%;
width: 100%;
opacity: 0;
left: 0;
right: 0;
top:0;
bottom: 0;
}
Expanding on #mvp's solution with unobtrusive javascript in mind, here's the approach:
HTML:
<input type="text" placeholder="Date" class="js-text-date-toggle">
Javascript:
$('.js-text-date-toggle').on('focus', function() {
$(this).attr('type', 'date');
}).on('blur', function() {
$(this).attr('type', 'text');
});
I think all you have to do is change the model to say the date field is nullable and then put [Required] on it if it is required. If you do this the placeholder text does appear.
Hey so I ran into the same issue last night and figured out a combination of all of your answer and some sparkling magic are doing a good job:
The HTML:
<input type="date" name="flb5" placeholder="Datum" class="datePickerPlaceHolder"/>
The CSS:
#media(max-width: 1024px) {
input.datePickerPlaceHolder:before {
color: #A5A5A5; //here you have to match the placeholder color of other inputs
content: attr(placeholder) !important;
}
}
The jQuery:
$(document).ready(function() {
$('input[type="date"]').change(function(){
if($(this).val().length < 1) {
$(this).addClass('datePickerPlaceHolder');
} else {
$(this).removeClass('datePickerPlaceHolder');
}
});
});
Explanation:
So, what is happening here, first of all in the HTML, this is pretty straight forward just doing a basic HMTL5-date-input and set a placeholder.
Next stop: CSS, we are setting a :before-pseudo-element to fake our placeholder, it just takes the placeholder's attribute from the input itself. I made this only available down from a viewport width of 1024px - why im going to tell later.
And now the jQuery, after refactoring a couple of times I came up with this bit of code which will check on every change if there is a value set or not, if its not it will (re-)add the class, vice-versa.
KNOW ISSUES:
there is a problem in chrome with its default date-picker, thats what the media-query is for. It will add the placeholder infront of the default 'dd.mm.yyyy'-thing. You could also set the placeholder of the date-input to 'date: ' and adjust the color incase of no value inside the input...for me this resulted in some other smaller issues so i went with just not showing it on 'bigger' screens
hope that helps!
cheerio!
From Angular point of view I managed to put a placeholder in input type date element.
First of all I defined the following css:
.placeholder {
color: $text-grey;
}
input[type='date']::before {
content: attr(placeholder);
}
input::-webkit-input-placeholder {
color: $text-grey;
}
The reason why this is neccessary is that if css3 content has different color that the normal placeholder, so I had to use a common one.
<input #birthDate
class="birthDate placeholder"
type="date"
formControlName="birthDate"
placeholder="{{getBirthDatePlaceholder() | translate}}"
[class.error]="!onboardingForm.controls.birthDate.valid && onboardingForm.controls.birthDate.dirty"
autocomplete="off"
>
Then in the template used a viewchild birthDate attribute, to be able to access this input from the component. And defined an angular expression on the placeholder attribute, which will decide if we show the placeholder or not. This is the major drawback of the solution, is that you have to manage the visibility of the placeholder.
#ViewChild('birthDate') birthDate;
getBirthDatePlaceholder() {
if (!this.birthDate) {
return;
} else {
return this.birthDate.nativeElement.value === '' ?
'ONBOARDING_FORM_COMPONENT.HINT_BIRTH_DATE' :
'';
}
}
<input placeholder="Date" type="text" onMouseOver="(this.type='date')" onMouseOut="(this.type='text')" id="date" class="form-control">
Revised code of mumthezir
If you're only concerned with mobile:
input[type="date"]:invalid:before{
color: rgb(117, 117, 117);
content: attr(placeholder);
}
I'm surprised there's only one answer with an approach similar to the one I used.
I got the inspiration from #Dtipson's comment on #Mumthezir VP's answer.
I use two inputs for this, one is a fake input with type="text" on which I set the placeholder, the other one is the real field with type="date".
On the mouseenter event on their container, I hide the fake input and show the real one, and I do the opposite on the mouseleave event. Obviously, I leave the real input visibile if it has a value set on it.
I wrote the code to use pure Javascript but if you use jQuery (I do) it's very easy to "convert" it.
// "isMobile" function taken from this reply:
// https://stackoverflow.com/a/20293441/3514976
function isMobile() {
try { document.createEvent("TouchEvent"); return true; }
catch(e) { return false; }
}
var deviceIsMobile = isMobile();
function mouseEnterListener(event) {
var realDate = this.querySelector('.real-date');
// if it has a value it's already visible.
if(!realDate.value) {
this.querySelector('.fake-date').style.display = 'none';
realDate.style.display = 'block';
}
}
function mouseLeaveListener(event) {
var realDate = this.querySelector('.real-date');
// hide it if it doesn't have focus (except
// on mobile devices) and has no value.
if((deviceIsMobile || document.activeElement !== realDate) && !realDate.value) {
realDate.style.display = 'none';
this.querySelector('.fake-date').style.display = 'block';
}
}
function fakeFieldActionListener(event) {
event.preventDefault();
this.parentElement.dispatchEvent(new Event('mouseenter'));
var realDate = this.parentElement.querySelector('.real-date');
// to open the datepicker on mobile devices
// I need to focus and then click on the field.
realDate.focus();
realDate.click();
}
var containers = document.getElementsByClassName('date-container');
for(var i = 0; i < containers.length; ++i) {
var container = containers[i];
container.addEventListener('mouseenter', mouseEnterListener);
container.addEventListener('mouseleave', mouseLeaveListener);
var fakeDate = container.querySelector('.fake-date');
// for mobile devices, clicking (tapping)
// on the fake input must show the real one.
fakeDate.addEventListener('click', fakeFieldActionListener);
// let's also listen to the "focus" event
// in case it's selected using a keyboard.
fakeDate.addEventListener('focus', fakeFieldActionListener);
var realDate = container.querySelector('.real-date');
// trigger the "mouseleave" event on the
// container when the value changes.
realDate.addEventListener('change', function() {
container.dispatchEvent(new Event('mouseleave'));
});
// also trigger the "mouseleave" event on
// the container when the input loses focus.
realDate.addEventListener('blur', function() {
container.dispatchEvent(new Event('mouseleave'));
});
}
.real-date {
display: none;
}
/* a simple example of css to make
them look like it's the same element */
.real-date,
.fake-date {
width: 200px;
height: 20px;
padding: 0px;
}
<div class="date-container">
<input type="text" class="fake-date" placeholder="Insert date">
<input type="date" class="real-date">
</div>
I tested this also on an Android phone and it works, when the user taps on the field the datepicker is shown. The only thing is, if the real input had no value and the user closes the datepicker without choosing a date, the input will remain visible until they tap outside of it. There's no event to listen to to know when the datepicker closes so I don't know how to solve that.
I don't have an iOS device to test it on.
This might help in some situation.
<input type="text" id="date" onclick="this.type='date'" onblur="this.type='text'" placeholder="Date" class="textbox-n" name="myDate" />
HTML:
<div>
<input class="ui-btn ui-btn-icon-right ui-corner-all ui-icon-calendar ui-shadow" id="inputDate" type="date"/>
<h3 id="placeholder-inputDate">Date Text</h3>
</div>
JavaScript:
$('#inputDate').ready(function () {
$('#placeholder-inputDate').attr('style'
, 'top: ' + ($('#placeholder-inputDate').parent().position().top + 10)
+ 'px; left: ' + ($('#placeholder-inputDate').parent().position().left + 0) + 'px; position: absolute;');
$('#inputDate').attr('style'
, 'width: ' + ($('#placeholder-inputDate').width() + 32) + 'px;');
});
Here is another possible hack not using js and still using css content. Note that as :after is not supported on some browser for inputs, we need to select the input in another way, same for content attr('')
input[type=date]:invalid+span:after {
content:"Birthday";
position:absolute;
left:0;
top:0;
}
input[type=date]:focus:invalid+span:after {
display:none;
}
input:not(:focus):invalid {
color:transparent;
}
label.wrapper {
position:relative;
}
<label class="wrapper">
<input
type="date"
required="required"
/>
<span></span>
</label>

restrict breaks or excessive spaces in text area?

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

Is there any way to change input type="date" format?

By default, the input type="date" shows date as YYYY-MM-DD.
The question is, is it possible to force it's format to something like: DD-MM-YYYY?
It is impossible to change the format
We have to differentiate between the over the wire format and the browser's presentation format.
Wire format
The HTML5 date input specification refers to the RFC 3339 specification, which specifies a full-date format equal to: yyyy-mm-dd. See section 5.6 of the RFC 3339 specification for more details.
This format is used by the value HTML attribute and DOM property and is the one used when doing an ordinary form submission.
Presentation format
Browsers are unrestricted in how they present a date input. At the time of writing Chrome, Edge, Firefox, and Opera have date support (see here). They all display a date picker and format the text in the input field.
Desktop devices
For Chrome, Firefox, and Opera, the formatting of the input field's text is based on the browser's language setting. For Edge, it is based on the Windows language setting. Sadly, all web browsers ignore the date formatting configured in the operating system. To me this is very strange behaviour, and something to consider when using this input type. For example, Dutch users that have their operating system or browser language set to en-us will be shown 01/30/2019 instead of the format they are accustomed to: 30-01-2019.
Internet Explorer 9, 10, and 11 display a text input field with the wire format.
Mobile devices
Specifically for Chrome on Android, the formatting is based on the Android display language. I suspect that the same is true for other browsers, though I've not been able to verify this.
Since this question was asked quite a few things have happened in the web realm, and one of the most exciting is the landing of web components. Now you can solve this issue elegantly with a custom HTML5 element designed to suit your needs. If you wish to override/change the workings of any html tag just build yours playing with the shadow dom.
The good news is that there’s already a lot of boilerplate available so most likely you won’t need to come up with a solution from scratch. Just check what people are building and get ideas from there.
You can start with a simple (and working) solution like datetime-input for polymer that allows you to use a tag like this one:
<date-input date="{{date}}" timezone="[[timezone]]"></date-input>
or you can get creative and pop-up complete date-pickers styled as you wish, with the formatting and locales you desire, callbacks, and your long list of options (you’ve got a whole custom API at your disposal!)
Standards-compliant, no hacks.
Double-check the available polyfills, what browsers/versions they support, and if it covers enough % of your user base… It's 2018, so chances are it'll surely cover most of your users.
Hope it helps!
As previously mentioned it is officially not possible to change the format. However it is possible to style the field, so (with a little JS help) it displays the date in a format we desire. Some of the possibilities to manipulate the date input is lost this way, but if the desire to force the format is greater, this solution might be a way. A date fields stays only like that:
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
The rest is a bit of CSS and JS: http://jsfiddle.net/g7mvaosL/
$("input").on("change", function() {
this.setAttribute(
"data-date",
moment(this.value, "YYYY-MM-DD")
.format( this.getAttribute("data-date-format") )
)
}).trigger("change")
input {
position: relative;
width: 150px; height: 20px;
color: white;
}
input:before {
position: absolute;
top: 3px; left: 3px;
content: attr(data-date);
display: inline-block;
color: black;
}
input::-webkit-datetime-edit, input::-webkit-inner-spin-button, input::-webkit-clear-button {
display: none;
}
input::-webkit-calendar-picker-indicator {
position: absolute;
top: 3px;
right: 0;
color: black;
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09">
It works nicely on Chrome for desktop, and Safari on iOS (especially desirable, since native date manipulators on touch screens are unbeatable IMHO). Didn't check for others, but don't expect to fail on any Webkit.
It's important to distinguish two different formats:
The RFC 3339/ISO 8601 "wire format": YYYY-MM-DD. According to the HTML5 specification, this is the format that must be used for the input's value upon form submission or when requested via the DOM API. It is locale and region independent.
The format displayed by the user interface control and accepted as user input. Browser vendors are encouraged to follow the user's preferences selection. For example, on Mac OS with the region "United States" selected in the Language & Text preferences pane, Chrome 20 uses the format "m/d/yy".
The HTML5 specification does not include any means of overriding or manually specifying either format.
I found a way to change format, it's a tricky way, I just changed the appearance of the date input fields using just a CSS code.
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
input[type="date"]::-webkit-datetime-edit-year-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 56px;
}
input[type="date"]::-webkit-datetime-edit-month-field{
position: absolute !important;
border-left:1px solid #8c8c8c;
padding: 2px;
color:#000;
left: 26px;
}
input[type="date"]::-webkit-datetime-edit-day-field{
position: absolute !important;
color:#000;
padding: 2px;
left: 4px;
}
<input type="date" value="2019-12-07">
I believe the browser will use the local date format. Don't think it's possible to change. You could of course use a custom date picker.
Google Chrome in its last beta version finally uses the input type=date, and the format is DD-MM-YYYY.
So there must be a way to force a specific format. I'm developing a HTML5 web page and the date searches now fail with different formats.
I searched this issue 2 years ago, and my google searches leads me again to this question.
Don't waste your time trying to handle this with pure JavaScript. I wasted my time trying to make it dd/mm/yyyy. There's no complete solutions that fits with all browsers. So I recommend to use momentJS / jQuery datepicker or tell your client to work with the default date format instead
Browsers obtain the date-input format from user's system date format.
(Tested in supported browsers, Chrome, Edge.)
As there is no standard defined by specs as of now to change the style of date control, it~s not possible to implement the same in browsers.
Users can type a date value into the text field of an input[type=date] with the date format shown in the box as gray text. This format is obtained from the operating system's setting. Web authors have no way to change the date format because there currently is no standards to specify the format.
So no need to change it, if we don't change anything, users will see the date-input's format same as they have configured in the system/device settings and which they are comfortable with or matches with their locale.
Remember, this is just the UI format on the screen which users see, in your JavaScript/backend you can always keep your desired format to work with.
To change the format in Chrome (e.g. from US "MM/DD/YYYY" to "DD/MM/YYYY") you go to >Settings >Advanced >Add language (choose English UK). Then:
The browser gets restarted and you will find date input fields like this: ´25/01/2022
Refer google developers page on same.
WHATWG git hub query on same
Test using below date input:
<input type="date" id="dob" value=""/>
Try this if you need a quick solution To make yyyy-mm-dd go "dd- Sep -2016"
1) Create near your input one span class (act as label)
2) Update the label everytime your date is changed by user, or when need to load from data.
Works for webkit browser mobiles and pointer-events for IE11+ requires jQuery and Jquery Date
$("#date_input").on("change", function () {
$(this).css("color", "rgba(0,0,0,0)").siblings(".datepicker_label").css({ "text-align":"center", position: "absolute",left: "10px", top:"14px",width:$(this).width()}).text($(this).val().length == 0 ? "" : ($.datepicker.formatDate($(this).attr("dateformat"), new Date($(this).val()))));
});
#date_input{text-indent: -500px;height:25px; width:200px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.min.js"></script>
<input id ="date_input" dateformat="d M y" type="date"/>
<span class="datepicker_label" style="pointer-events: none;"></span>
After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
As said, the <input type=date ... > is not fully implemented in most browsers, so let's talk about webkit like browsers (chrome).
Using linux, you can change it by changing the environment variable LANG, LC_TIME don't seems to work(for me at least).
You can type locale in a terminal to see your current values. I think the same concept can be applied to IOS.
eg:
Using:
LANG=en_US.UTF-8 /opt/google/chrome/chrome
The date is showed as mm/dd/yyyy
Using:
LANG=pt_BR /opt/google/chrome/chrome
The date is showed as dd/mm/yyyy
You can use http://lh.2xlibre.net/locale/pt_BR/ (change pt_BR by your locale) to create you own custom locale and format your dates as you want.
A nice more advanced reference on how change default system date is:
https://ccollins.wordpress.com/2009/01/06/how-to-change-date-formats-on-ubuntu/
and
https://askubuntu.com/questions/21316/how-can-i-customize-a-system-locale
You can see you real current date format using date:
$ date +%x
01-06-2015
But as LC_TIME and d_fmt seems to be rejected by chrome ( and I think it's a bug in webkit or chrome ), sadly it don't work. :'(
So, unfortunately the response, is IF LANG environment variable do not solve your problem, there is no way yet.
It's not possible to change web-kit browsers use user's computer or mobiles default date format.
But if you can use jquery and jquery UI there is a date-picker which is designable and can be shown in any format as the developer wants.
the link to the jquery UI date-picker is
on this page http://jqueryui.com/datepicker/ you can find demo as well as code and documentation or documentation link
Edit:-I find that chrome uses language settings that are by default equal to system settings but the user can change them but developer can't force users to do so so you have to use other js solutions like I tell you can search the web with queries like javascript date-pickers or jquery date-picker
Since the post is active 2 Months ago. so I thought to give my input as well.
In my case i recieve date from a card reader which comes in dd/mm/yyyy format.
what i do.
E.g.
var d="16/09/2019" // date received from card
function filldate(){
document.getElementById('cardexpirydate').value=d.split('/').reverse().join("-");
}
<input type="date" id="cardexpirydate">
<br /><br />
<input type="button" value="fill the date" onclick="filldate();">
what the code do:
it splits the date which i get as dd/mm/yyyy (using split()) on basis of "/" and makes an array,
it then reverse the array (using reverse()) since the date input supports the reverse
of what i get.
then it joins (using join())the array to a string according the
format required by the input field
All this is done in a single line.
i thought this will help some one so i wrote this.
I adjusted the code from Miguel to make it easier to understand
and I want to share it with people who have problems like me.
Try this for easy and quick way
$("#datePicker").on("change", function(e) {
displayDateFormat($(this), '#datePickerLbl', $(this).val());
});
function displayDateFormat(thisElement, datePickerLblId, dateValue) {
$(thisElement).css("color", "rgba(0,0,0,0)")
.siblings(`${datePickerLblId}`)
.css({
position: "absolute",
left: "10px",
top: "3px",
width: $(this).width()
})
.text(dateValue.length == 0 ? "" : (`${getDateFormat(new Date(dateValue))}`));
}
function getDateFormat(dateValue) {
let d = new Date(dateValue);
// this pattern dd/mm/yyyy
// you can set pattern you need
let dstring = `${("0" + d.getDate()).slice(-2)}/${("0" + (d.getMonth() + 1)).slice(-2)}/${d.getFullYear()}`;
return dstring;
}
.date-selector {
position: relative;
}
.date-selector>input[type=date] {
text-indent: -500px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date-selector">
<input id="datePicker" class="form-control" type="date" onkeydown="return false" />
<span id="datePickerLbl" style="pointer-events: none;"></span>
</div>
NEW in Firefox (since unknown version), in Settings > Language, they have added an option: Use your operating system settings for “Spanish (Spain)” to format dates, times, numbers, and measurements
This option will use the Operating System's locale to display dates! Too bad it does not come enabled by default (maybe from a fresh install it does?)
Angular devs (and maybe others) could consider this partial solution.
My strategy was to detect the focus state of the input field, and switch between date and text type accordingly. The obvious downside is that the date format will change on input focus.
It's not perfect but insures a decent level of consistency especially if you have some dates displayed as text and also some date inputs in your web app. It's not going to be very helpful if you have just one date input.
<input class="form-control"
[type]="myInputFocus ? 'date' : 'text'"
id="myInput"
name="myInput"
#myInput="ngModel"
[(ngModel)]="myDate"
(focus)="myInputFocus = true"
(blur)="myInputFocus = false">
And simply declare myInputFocus = false at the beginning of you component class.
Obviously point myDate to your desired control.
Thanks to #safi eddine and #Hezbullah Shah
Datepicker with VanillaJS and CSS.
CSS - STYLE:
/*================== || Date Picker ||=======================================================================================*/
/*-------Removes the // Before dd - day------------------------*/
input[type="date"]::-webkit-datetime-edit-text
{
color: transparent;
}
/*------- DatePicker ------------------------*/
input[type="date"] {
background-color: aqua;
border-radius: 4px;
border: 1px solid #8c8c8c;
font-weight: 900;
}
/*------- DatePicker - Focus ------------------------*/
input[type="date"]:focus
{
outline: none;
box-shadow: 0 0 0 3px rgba(21, 156, 228, 0.4);
}
input[type="date"]::-webkit-datetime-edit, input[type="date"]::-webkit-inner-spin-button, input[type="date"]::-webkit-clear-button {
color: #fff;
position: relative;
}
/*------- Year ------------------------*/
input[type="date"]::-webkit-datetime-edit-year-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 56px;
}
/*------- Month ------------------------*/
input[type="date"]::-webkit-datetime-edit-month-field {
position: absolute !important;
border-left: 1px solid #8c8c8c;
padding: 2px;
color: #000;
left: 26px;
}
/*------- Day ------------------------*/
input[type="date"]::-webkit-datetime-edit-day-field {
position: absolute !important;
color: #000;
padding: 2px;
left: 4px;
}
JAVASCRIPT:
// ================================ || Format Date Picker || ===========================================================
function GetFormatedDate(datePickerID)
{
let rawDate = document.getElementById(datePickerID).value; // Get the Raw Date
return rawDate.split('-').reverse().join("-"); // Reverse the date
}
USING:
document.getElementById('datePicker').onchange = function () { alert(GetFormatedDate('datePicker')); }; // The datepickerID
const birthday = document.getElementById("birthday");
const button = document.getElementById("wishBtn");
button.addEventListener("click", () => {
let dateValue = birthday.value;
// Changing format :)
dateValue = dateValue.split('-').reverse().join('-');
alert(`Happy birthday king/Queen of ${dateValue}`);
});
<input type="date" id="birthday" name="birthday" value="2022-10-10"/>
<button id="wishBtn">Clik Me</button>
Not really no.
Hackable but very slim & customizable solution would be to:
Hide date input (CSS visibility: hidden) (still shows calendar popup tho)
Put a text input on top of it
On text input click, use JS to get date input element & call .showPicker()
store date picker value elsewhere
show value in your custom format you want in the text input
Here's some sample react code:
<div style={{ width: "100%", position: "relative" }}>
<input type="date" className={`form-control ${props.filters[dateFromAccessor] ? '' : 'bh-hasNoValue'}`} id={`${accessor}-date-from`} placeholder='from'
value={toDate(props.filters[dateFromAccessor])} style={{ marginRight: 0, visibility: "hidden" }}
onChange={e => {
props.setFilters({ ...props.filters, [dateFromAccessor]: inputsValueToNumber(e) })
}} />
<input type="text" className="form-control" readOnly
style={{ position: "absolute", top: 0, left: 0, width: "100%", height: "100%", backgroundColor: "white" }}
value={toDate(props.filters[dateFromAccessor])}
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
(document.getElementById(`${accessor}-date-from`) as any)?.showPicker();
}}></input>
</div>
I know it's an old post but it come as first suggestion in google search, short answer no, recommended answer user a custom date piker , the correct answer that i use is using a text box to simulate the date input and do any format you want, here is the code
<html>
<body>
date :
<span style="position: relative;display: inline-block;border: 1px solid #a9a9a9;height: 24px;width: 500px">
<input type="date" class="xDateContainer" onchange="setCorrect(this,'xTime');" style="position: absolute; opacity: 0.0;height: 100%;width: 100%;"><input type="text" id="xTime" name="xTime" value="dd / mm / yyyy" style="border: none;height: 90%;" tabindex="-1"><span style="display: inline-block;width: 20px;z-index: 2;float: right;padding-top: 3px;" tabindex="-1">▼</span>
</span>
<script language="javascript">
var matchEnterdDate=0;
//function to set back date opacity for non supported browsers
window.onload =function(){
var input = document.createElement('input');
input.setAttribute('type','date');
input.setAttribute('value', 'some text');
if(input.value === "some text"){
allDates = document.getElementsByClassName("xDateContainer");
matchEnterdDate=1;
for (var i = 0; i < allDates.length; i++) {
allDates[i].style.opacity = "1";
}
}
}
//function to convert enterd date to any format
function setCorrect(xObj,xTraget){
var date = new Date(xObj.value);
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
if(month!='NaN'){
document.getElementById(xTraget).value=day+" / "+month+" / "+year;
}else{
if(matchEnterdDate==1){document.getElementById(xTraget).value=xObj.value;}
}
}
</script>
</body>
</html>
1- please note that this method only work for browser that support date type.
2- the first function in JS code is for browser that don't support date type and set the look to a normal text input.
3- if you will use this code for multiple date inputs in your page please change the ID "xTime" of the text input in both function call and the input itself to something else and of course use the name of the input you want for the form submit.
4-on the second function you can use any format you want instead of day+" / "+month+" / "+year for example year+" / "+month+" / "+day and in the text input use a placeholder or value as yyyy / mm / dd for the user when the page load.

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