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>
I was wondering how can i automatically make first character of the word in an input area
Currently my code is
Name:<input type='text' name='name' class='name' placeholder='Enter your name here'/>
You can try this: DEMO
Name:<input type='text' name='name' class='name' style="text-transform: capitalize;" placeholder='Enter your name here'/>
or add text-transform: capitalize; in your name in css.
The problem with using CSS (text-transform: capitalize) is that when the form gets submitted, the name will be submitted with a lowercase name.
The CSS works well for cosmetics but not for functionality.
You can use jQuery to force capitalization functionality in your input boxes:
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function($) {
$('.name').keyup(function(event) {
var textBox = event.target;
var start = textBox.selectionStart;
var end = textBox.selectionEnd;
textBox.value = textBox.value.charAt(0).toUpperCase() + textBox.value.slice(1).toLowerCase();
textBox.setSelectionRange(start, end);
});
});
</script>
Put this code between the <head> </head> on the page where your form is located.
Above jQuery will also force ALL CAPS to Capitalize.
Check out the Fiddle here: https://jsfiddle.net/cgaybba/6rps8hfo/
I think it should also be mentioned that if the form is on mobile, you can just use the autocapitalize attribute. see here for documentation
Try this
HTML CODE
<input type='text' name='name' class='name' placeholder='Enter your name here'/>
CSS CODE
<style>
.name
{
text-transform:capitalize;
}
</style>
Update you css
.name { text-transform: capitalize; }
The good side of using JS is that when the user submits the form, it retains the capitalized input values, but using css when the form is submitted, it looses the capitalized values (for frontend only).
Note for CSS: make sure you don't have any overriding styles else use !important.
//For CSS
input { text-transform: capitalize }
//For JS
$('.your-input').on('change keydown paste', function(e) {
if (this.value.length = 1) {}
var $this_val = $(this).val();
this_val = $this_val.toLowerCase().replace(/\b[a-z]/g, function(char) {
return char.toUpperCase();
});
$(this).val(this_val);
});
Just include → style="text-transform:capitalize;" inside your input tag.
Is there a way I can also set some label text for each steps in the HTML5 type=range control. Basically I have a range control <input type="range" step=1 min=0 max=4> and for each steps I want some label to be shown in the control. Is there a way to do this?
I've put together for you.
// define a lookup for what text should be displayed for each value in your range
var rangeValues =
{
"1": "You've selected option 1!",
"2": "...and now option 2!",
"3": "...stackoverflow rocks for 3!",
"4": "...and a custom label 4!"
};
$(function () {
// on page load, set the text of the label based the value of the range
$('#rangeText').text(rangeValues[$('#rangeInput').val()]);
// setup an event handler to set the text when the range value is dragged (see event for input) or changed (see event for change)
$('#rangeInput').on('input change', function () {
$('#rangeText').text(rangeValues[$(this).val()]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="range" id="rangeInput" name="rangeInput" step="1" min="1" max="4">
<label id="rangeText" />
I guess the easiest solution (plain Javascript) is:
<fieldset>
<label for="rangeVal">resolution (dpi):</label>
<input type ="range" max="1000" min="20"
oninput="document.getElementById('rangeValLabel').innerHTML = this.value;"
step="1" name="rangeVal" id="rangeVal" value="200">
</input>
<em id="rangeValLabel" style="font-style: normal;"></em>
</fieldset>
This code does not need jQuery nor CSS and should work on any browser that supports the range input type.
Here's an alternative solution, no jQuery required. Uses the HTML5 oninput event handler, and valueAsNumber property of the input element.
Works on my machine certification: Chrome v54
<form name="myform" oninput="range1value.value = range1.valueAsNumber">
<input name="range1" type="range" step="1" min="0" max="4" value="1">
<output name="range1value" for="range1" >1</output>
</form>
OP,
I put together a demo that uses a range input with corresponding <p> tags that act as both labels for the current state of the slider, as well as triggers to change the slider's value.
Plunk
http://plnkr.co/edit/ArOkBVvUVUvtng1oktZG?p=preview.
HTML Markup
<div class="rangeWrapper">
<input id="slide" type="range" min="1" max="4" step="1" value="1" />
<p class="rangeLabel selected">Label A</p>
<p class="rangeLabel">Label B</p>
<p class="rangeLabel">Label C</p>
<p class="rangeLabel">Label D</p>
</div>
Javascript
$(document).ready(function(){
$("input[type='range']").change(function() {
slider = $(this);
value = (slider.val() -1);
$('p.rangeLabel').removeClass('selected');
$('p.rangeLabel:eq(' + value + ')').addClass('selected');
});
$('p.rangeLabel').bind('click', function(){
label = $(this);
value = label.index();
$("input[type='range']").attr('value', value)
.trigger('change');
});
});
CSS
input[type="range"] {
width: 100%;
}
p.rangeLabel {
font-family: "Arial", sans-serif;
padding: 5px;
margin: 5px 0;
background: rgb(136,136,136);
font-size: 15px;
line-height 20px;
}
p.rangeLabel:hover {
background-color: rgb(3, 82, 3);
color: #fff;
cursor: pointer;
}
p.rangeLabel.selected {
background-color: rgb(8, 173, 8);
color: rgb(255,255,255);
}
Also worth nothing, if you're interested in showing the current value as a label/flag to the user, (instead of many) there's a great article by Chris Coyier on value bubbles for range sliders.
There is no native way of doing it. And as input[type=range] is very poorly supported, I will recommend using jQuery UI slider and the way of attaching labels found here in answer.
You can use jSlider. Its a jQuery slider plugin for range inputs.
https://github.com/egorkhmelev/jslider
Just check out the demos and documentation. Hope this helps.
FWIW the standard (HTML 5.1, HTML Living Standard), specifies a label attribute for options when using a datalist. Sample code here.
This isn't implemented by any browser yet.
I think its a easy question, but i dont know how to search this question in google
I need a background text in a input-text field. Like: Insert Your Name.
And when i press in to the field to insert my name, the text disappears
Okay, thanks for the solution.
<input id="textfield" name="textfield" type="text" placeholder="correct" />
Now i get i second question. How can i change the color of the placeholder?
Here's my text-area:
http://jsfiddle.net/wy8cP/1/
Here is how you can get a placeholder using HTML5:
<input id="textfield" name="textfield" type="text" placeholder="enter something" />
EDIT:
I no longer recommend hacking together your own polyfills as I showed below. You should use Modernizr to first detect whether a polyfill is needed in the first place, and then activate a polyfill library that fits your needs. There is a good selection of placeholder polyfills listed in the Modernizr wiki.
ORIGINAL (contd):
And here is a polyfill for compatibility:
<input id="textfield" name="textfield" type="text" value="enter something" onfocus="if (this.value == 'enter something') {this.value = '';}" onblur="if (this.value == '') {this.value = 'enter something';}">
http://jsfiddle.net/q3V4E/1/
A better shim approach is to run this script on page load, and put your placeholders in the data-placeholder attribute, so your markup looks like this:
<input id="textfield" name="textfield" type="text" data-placeholder="enter something">
and your js looks like this:
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = inputs[i].getAttribute('data-placeholder');
inputs[i].addEventListener('focus', function() {
if (this.value == this.getAttribute('data-placeholder')) {
this.value = '';
}
});
inputs[i].addEventListener('blur', function() {
if (this.value == '') {
this.value = this.getAttribute('data-placeholder');
}
});
}
http://jsfiddle.net/q3V4E/4/
HTML5 provides a placeholder attribute that addresses this particular issue. See this link for more information (JSFiddle)
<input type="text" placeholder="insert your name" />
You can always provide a non-HTML5 javascript fallback, like the one explained here, or in None jquery placeholder fallback? if you aren't using JQuery.
I think you are looking for HTML5 form field placeholder... :)
http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text
The jquery version of the non-html 5 accepted answer:
var inputs = $("input[type='text']", context);
$.each(inputs, function (i, obj) {
$(obj).val($(obj).attr('data-placeholder'));
$(obj).on('focus', function () {
if ($(this).val() == $(this).attr('data-placeholder')) {
$(this).val('');
}
});
$(obj).on('blur', function () {
if ($(this).val() == '') {
$(this).val($(this).attr('data-placeholder'));
}
});
});
Changing the color of the placeholder can be achieved with CSS:
::-webkit-input-placeholder { /* Chrome/Opera/Safari */
color: pink;
}
::-moz-placeholder { /* Firefox 19+ */
color: pink;
}
:-ms-input-placeholder { /* IE 10+ */
color: pink;
}
:-moz-placeholder { /* Firefox 18- */
color: pink;
}
Source: https://css-tricks.com/almanac/selectors/p/placeholder/
For non-HTML5, I suggest a nice javascript solution such as toggleval.js - this allows you not to have to do every input field inline, yourself; it would be global.
http://snipplr.com/view/9077/
The script you would call to after that would be something like this:
<script type="text/javascript">
$(document).ready(function() {
// Input Box ToggleVal
$("input[type=text]").toggleVal();
$("input[type=password]").toggleVal();
});
</script>
I am wondering whether it is possible to set the date format in the html <input type="date"></input> tag... Currently it is yyyy-mm-dd, while I need it in the dd-mm-yyyy format.
I found same question or related question on stackoverflow
Is there any way to change input type=“date” format?
I found one simple solution, You can not give particulate Format but you can customize Like this.
HTML Code:
<body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>
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:
If you're using jQuery, here's a nice simple method
$("#dateField").val(new Date().toISOString().substring(0, 10));
Or there's the old traditional way:
document.getElementById("dateField").value = new Date().toISOString().substring(0, 10)
Why not use the html5 date control as it is, with other attributes that allows it work ok on browsers that support date type and still works on other browsers like firefox that is yet to support date type
<input type="date" name="input1" placeholder="YYYY-MM-DD" required pattern="[0-9]{4}-[0-9]{2}-[0-9]{2}" title="Enter a date in this formart YYYY-MM-DD"/>
$('input[type="date"]').change(function(){
alert(this.value.split("-").reverse().join("-"));
});
I made a lot of research and I don't think one can force format of the <input type="date">.
The browser select the local format, and depending on user settings, if the user's language is in English, the date will be displayed to the English format (mm/dd/yyyy).
In my opinion, the best solution is to use a plugin to control the display.
Jquery DatePicker seems a good option since you can force the localization, date format ...
I came up with a slightly different answer than anything above that I've read.
My solution uses a small bit of JavaScript and an html input.
The Date accepted by an input results in a String formatted as 'yyyy-mm-dd'. We can split it and place it properly as a new Date().
Here is basic HTML:
<form id="userForm">
<input type="text" placeholder="1, 2, 3, 4, 5, 6" id="userNumbers" />
<input type="date" id="userDate" />
<input type="submit" value="Track" />
</form>
Here is basic JS:
let userDate = document.getElementById('userDate').value.split('-'),
parsedDate = new Date((`${userDate[1]}-${userDate[2]}-${userDate[0]}`));
You can format the date any way you like. You can create a new Date() and grab all the info from there... or simply use 'userDate[]' to build your string.
Keep in mind, some ways that a date is entered into 'new Date()' produces an unexpected result. (ie - one day behind)
For formatting in mm-dd-yyyy:
aa = date.split("-")
date = aa[1]+'-'+aa[2]+'-'+aa[0]
Here's one option. When the user is entering the date, the function reformats it. When they click the submit button, it populates the result div with the date in the format you're looking for.
<div id="result"></div>
<p>Enter some text:
<input type="date" name="txt" id="datefield" onchange="dateval(value)"></p>
<button onclick="postdate()">submit</button>
<script>
var a;
// Set the *value* of the input element to
// yyyy-mm-dd (text is unchanged)
function dateval(val) {
var dv = document.getElementById("datefield");
a = val.split("-").reverse().join("-");
dv.type = "text";
dv.value = a;
}
// Extract the yyyy-mm-dd value from the inpuut element,
// format it to dd-mm-yyyy and put it in the div
function postdate() {
var dv = document.getElementById("datefield");
var z = a.split("-").reverse().join("-");
document.getElementById("result").innerHTML = a;
dv.type = "date";
dv.value = z;
}
</script>
I don't know this for sure, but I think this is supposed to be handled by the browser based on the user's date/time settings. Try setting your computer to display dates in that format.
short direct answer is no or not out of the box but i have come up with a method to use a text box and pure JS code 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.
We can change this yyyy-mm-dd format to dd-mm-yyyy in javascript by using split method.
let dateyear= "2020-03-18";
let arr = dateyear.split('-') //now we get array of these and we can made in any format as we want
let dateFormat = arr[2] + "-" + arr[1] + "-" + arr[0] //In dd-mm-yyyy format
Clean implementation with no dependencies. https://jsfiddle.net/h3hqydxa/1/
<style type="text/css">
.dateField {
width: 150px;
height: 32px;
border: none;
position: absolute;
top: 32px;
left: 32px;
opacity: 0.5;
font-size: 12px;
font-weight: 300;
font-family: Arial;
opacity: 0;
}
.fakeDateField {
width: 100px; /* less, so we don't intercept click on browser chrome for date picker. could also change this at runtime */
height: 32px; /* same as above */
border: none;
position: absolute; /* position overtop the date field */
top: 32px;
left: 32px;
display: visible;
font-size: 12px; /* same as above */
font-weight: 300; /* same as above */
font-family: Arial; /* same as above */
line-height: 32px; /* for vertical centering */
}
</style>
<input class="dateField" id="dateField" type="date"></input>
<div id="fakeDateField" class="fakeDateField"><em>(initial value)</em></div>
<script>
var dateField = document.getElementById("dateField");
var fakeDateField = document.getElementById("fakeDateField");
fakeDateField.addEventListener("click", function() {
document.getElementById("dateField").focus();
}, false);
dateField.addEventListener("focus", function() {
fakeDateField.style.opacity = 0;
dateField.style.opacity = 1;
});
dateField.addEventListener("blur", function() {
fakeDateField.style.opacity = 1;
dateField.style.opacity = 0;
});
dateField.addEventListener("change", function() {
// this method could be replaced by momentJS stuff
if (dateField.value.length < 1) {
return;
}
var date = new Date(dateField.value);
var day = date.getUTCDate();
var month = date.getUTCMonth() + 1; //zero-based month values
fakeDateField.innerHTML = (month < 10 ? "0" : "") + month + " / " + day;
});
</script>
Here is the solution:
<input type="text" id="end_dt"/>
$(document).ready(function () {
$("#end_dt").datepicker({ dateFormat: "MM/dd/yyyy" });
});
hopefully this will resolve the issue :)
The format of the date value is 'YYYY-MM-DD'. See the following example
<form>
<input value="2015-11-30" name='birthdate' type='date' class="form-control" placeholder="Date de naissance"/>
</form>
All you need is to format the date in php, asp, ruby or whatever to have that format.