Not showing placeholder for input type="date" field
Asked Answered
E

40

170

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">
Earsplitting answered 2/12, 2013 at 5:2 Comment(1)
Possible duplicate of placeholder for input type date html5Raimondo
E
258

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')"
      onblur="(this.type='text')"
      id="date" />
Earsplitting answered 3/12, 2013 at 4:53 Comment(12)
Seems like a nice feature, however clicking the field shows the onscreen keyboard instead of the datepicker. Nice try though.Dorrie
I tried that solution (using AngularJs in a template for directive) but got JavaScript errors in IE 11Abrasion
@MathijsSegers have you found a solution that NOT shows the keyboard? I tried this solutions here, but in iOS 6, 7 and 8, shows the keyboard for a little time and then shows the datepicker.Poree
Well yes a disgusting one. I added a span with the looks of a textfield at the datefield rendering it visible only on ios. The z index of the datepicker was higher than the span but alpha 0.01 in css. Onclick i'd reveal the datefield. It works but is kinda nasty.Dorrie
IE doesn't like or (at least pre IE11) even allow changing the type of an element once created. You'd be better off hiding/showing two different ones that you swap out.Herculaneum
I have noticed that this does not work on iOS devices, does someone have a solution for this?Loni
For cordova apps, use onmouseenter event instead of onfocus event, then, the date picker will open at the first clickEconomical
To stop the keyboard from showing on iOS use readonly="true" and then remove it onfocus. For more details see ma90's answer below: https://mcmap.net/q/143116/-not-showing-placeholder-for-input-type-quot-date-quot-fieldDivergence
I have tried this solution with react and didn't work . date picker won't show up at all for me . tried on chrome and firefox.Amalamalbena
<input type="date" onfocus="this.showPicker()"> this will open the date picker as well on click.Neuropsychiatry
Its good, but better:Gonfalonier
Yuri's answer below is a better approach. It works very well and uses just CSS.Daughterly
G
138

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" />
Gersham answered 15/5, 2014 at 16:18 Comment(7)
Thanks! This worked perfectly for me! Might I suggest making the field disabled, and then removing the disable on click? I was working in Angular, and wrote a scope function to change the type, and remove the disable, itll stop weird bugs when it somehow focuses on the text fieldHammerless
I am able to see the placeholder when it is out of focus, but to get the date picker, I need to click on it twice. How can I solve it?Silvertongued
The format of the date changes as it changes between type date/text. And, doesn't work on iOS devices.Provitamin
It's 2020 and we still need to use js for this... Wonder what is the problem in this type="date" placeholder and why it is not acting like the rest...Wadleigh
I've improved the onblur part, to only switch back to text, when the value remains empty: onblur="if(this.value==''){this.type='text'}"Platoon
Top. the best option, the onblur fix the issue of the first response.Shill
adding "required" to this doesn't work. People can still send the form without this being filled in.Zacharia
P
43

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':'')">
Portative answered 17/6, 2016 at 16:41 Comment(2)
This version doesn't mess with other classes <input type="date" placeholder="MY PLACEHOLDER" onchange="this.classList.toggle('has-value',this.value);">Calais
i used this and addedd input[type="date"]:not(:focus):not(.has-value):before to show the format while the input is focused (for people who type the date instead of selecting)Obtrusive
W
27

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;
}
Wardmote answered 2/6, 2016 at 13:13 Comment(0)
L
20

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.

Limn answered 4/2, 2015 at 16:47 Comment(4)
Excellent! Just have to set the initial state of the "full" class, e.g. if you're editing an existing date.Roundy
I suggest that we should use color: #aaa for a placeholder-like appearance on iOS. color: lightgray is just too light.Plunkett
Great answer! You code make the jQuery a bit more readible using toggleClass: $("#myel").on( "input" , function(){ $(this).toggleClass( "full" , $(this).val().length > 0 ); });Mcfarlin
Keep in mind that Firefox (and Edge?) does not support :before and :after on <input> elements. Chrome does, but this goes against the CSS spec.Plasmo
J
17

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>
Jinn answered 20/12, 2015 at 20:38 Comment(2)
Because it's not mentioned in this post, don't forget to add required to your input or the input will always be valid and this solution will not work.Mcilroy
"Required" means you can't then clear the date and see the placeholder that you've lavished all this care on. Nightmare.Symbiosis
C
14

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">
Ceceliacecil answered 21/6, 2019 at 15:44 Comment(0)
S
12

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.

Seashore answered 2/12, 2013 at 6:58 Comment(5)
then, what should i do?Earsplitting
@mvp, you should not use placeholder attribute, and put a <label> element associated to the input[type=date].Seashore
should it look like a place holder?Earsplitting
Labels and placeholders are 2 different things. I do not understand what you are suggesting here.Jameejamel
Link in answer is dead, giving "404 Not Found".Deviate
S
11

It works for me:

input[type='date']:after {
  content: attr(placeholder)
}
Shogun answered 14/1, 2015 at 11:43 Comment(5)
Only problem with this is removing the placeholder when you've selected a date. The place holder doesn't get removed.Humidity
On iOS 9.3, Safari will make the :after pseudo element disappear when a date is selected. So no need to remove the placeholderPlunkett
Just add onfocus="(this.placeholder='')" to remove the placeholder once the date is selected.Dying
Excellent!!! Worked for me too, adding the onfocus that @RobbieNolan has suggested worked perfecly.Idiomatic
just add this to hide the default placeholder of dd mm yyyy input::-webkit-datetime-edit{ display: none; }Febri
A
11

I used this with 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');
    });
});
Aromaticity answered 3/3, 2015 at 16:15 Comment(3)
please add explanation why it will helpSikora
@Davide Russo Abram : Please add explanation , how does it works ?Corvette
Thanks! Tough to be in 2k23 and know we still need this :)Croydon
C
9

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"> 
Curdle answered 24/7, 2018 at 6:42 Comment(0)
J
7

<input placeholder="01-01-2021" class="textbox-n" type="text" onfocus="(this.type='date')" onblur="(this.type='text')" id="date" />
Jourdain answered 22/6, 2021 at 16:19 Comment(1)
Why would you post an answer that is basically a cut and paste of the accepted answer from 2014? What is the reason for this? Are you just trying to con upvotes out of people?Zacharia
M
4

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();">
Metallist answered 4/9, 2014 at 8:35 Comment(2)
Even with this code, in iOS (tested on iOS 6, 7 and 8) shows the keyboard for a moment and then shows the datepicker. There is a way to NOT show the keyboard?Poree
@JabelMárquez You can use readonly="true" to stop the keyboard from showing... so something like this: <input type="text" name="date" value="" placeholder="Date" readonly="true" onfocus="this.removeAttribute('readonly');this.type='date';this.setAttribute('onfocus','');this.blur();this.focus();">. Has worked for me.Divergence
S
3

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.

Seyler answered 25/5, 2015 at 16:55 Comment(0)
I
3

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
}
Infiltrate answered 18/9, 2018 at 14:24 Comment(1)
the dd/mm/yyyy is still being displayed on Chrome (70).Lepley
R
2

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

Roanna answered 9/7, 2014 at 9:9 Comment(0)
T
2

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');
});
Tiemroth answered 30/9, 2014 at 18:37 Comment(0)
D
2

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

Daryl answered 30/7, 2015 at 15:1 Comment(0)
H
2

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"> 
Hargreaves answered 5/11, 2015 at 15:49 Comment(0)
S
2

You can

  1. set it as type text
  2. convert to date on focus
  3. make click on it
  4. ...let user check date
  5. on change store the value
  6. set input to type text
  7. 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" />
Scout answered 12/5, 2016 at 22:36 Comment(0)
U
2

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;
}
Umlaut answered 19/5, 2018 at 13:26 Comment(0)
R
1

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.

Redwood answered 24/8, 2015 at 16:24 Comment(0)
H
1

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!

Hooknosed answered 12/12, 2015 at 15:54 Comment(0)
A
1

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' :
    '';
  }
}
Amand answered 21/7, 2017 at 6:58 Comment(0)
V
1

<input placeholder="Date" type="text" onMouseOver="(this.type='date')" onMouseOut="(this.type='text')"  id="date" class="form-control">

Revised code of mumthezir

Vino answered 9/2, 2018 at 6:55 Comment(0)
C
1

If you're only concerned with mobile:

input[type="date"]:invalid:before{
    color: rgb(117, 117, 117);
    content: attr(placeholder);
}
Celinecelinka answered 23/3, 2018 at 17:14 Comment(0)
E
1

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://mcmap.net/q/42180/-how-to-detect-a-mobile-device-using-jquery
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.

Esperanto answered 30/3, 2020 at 17:26 Comment(0)
A
1

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" />
      
Austronesia answered 22/6, 2021 at 15:54 Comment(0)
P
0

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;');
});
Polyhydric answered 20/6, 2018 at 8:36 Comment(1)
Posting code without any explanation isn't welcome here. Please edit your post.Meuser
E
0

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>
Ejection answered 11/7, 2018 at 13:58 Comment(0)
K
0

This works for me using this as input element:

<input name="birthdate" class="" class="wpcf7-form-control wpcf7-date 
 wpcf7-validates-as-required wpcf7-validates-as-date birthdate" value="" 
 aria-required="true" aria-invalid="false" placeholder="birthdate *" 
 type="date">

This CSS shows a permanent placeholder. The selected value is shown after the placeholder.

input[type="date"]:before {
    content: attr(placeholder) !important;
    margin-right: 0.5em;
    display: block;
}
/* only for FF */
@-moz-document url-prefix() {
    input[type="date"]:before {
        content: attr(placeholder) !important;
        margin-right: 0.5em;
        display: block;
        position: absolute;
        left: 200px; /* please adopt */
    }
}

I use this solution for a Wordpress form with contact-form-7 plugin.

Ketron answered 24/8, 2018 at 11:17 Comment(0)
P
0

None of the solutions were working correctly for me on Chrome in iOS 12 and most of them are not tailored to cope with possible multiple date inputs on a page. I did the following, which basically creates a fake label over the date input and removes it on tap. I am also removing the fake label if viewport width is beyond 992px.

JS:

function addMobileDatePlaceholder() {
    if (window.matchMedia("(min-width: 992px)").matches) {
        $('input[type="date"]').next("span.date-label").remove();
        return false;
    }

    $('input[type="date"]').after('<span class="date-label" />');

    $('span.date-label').each(function() {
        var $placeholderText = $(this).prev('input[type="date"]').attr('placeholder');
        $(this).text($placeholderText);
    });

    $('input[type="date"]').on("click", function() {
        $(this).next("span.date-label").remove();
    });
}

CSS:

@media (max-width: 991px) {
    input[type="date"] {
        padding-left: calc(50% - 45px);
    }

    span.date-label {
        pointer-events: none;
        position: absolute;
        top: 2px;
        left: 50%;
        transform: translateX(-50%);
        text-align: center;
        height: 27px;
        width: 70%;
        padding-top: 5px;
    }
}
Picayune answered 16/5, 2019 at 11:3 Comment(0)
M
0

Below solution worked for me. I hope it will help to you as well.

*{
box-sizing:border-box;
}
  
::placeholder {
        opacity: 0;
        visibility: hidden;
        color: transparent;
  }
.box{
  min-height:500px;
}

.demo-field{
    margin-bottom: 1.25rem;
    position: relative;
  }

 input{
     display: block;
    width: 100%;
    padding: 0.75rem 0.75rem;
    font-size: 1rem;
  }
    
.floating-label {
    position: absolute;
    left: 10px;
    top: 14px;
    padding: 2px 4px;
    transition: all 0.3s ease;
    cursor: text;
    border-radius: 4px;
}
input:focus ~ .floating-label {
    top: -13px;
    left: 10px;
    transition: all 0.2s ease-in-out;
    background: #fff;
}
.demo-field .demo-input:not(:placeholder-shown).demo-input:not(:focus) ~ .floating-label {
    top: -13px;
    left: 10px;
    background: #fff;
    transition: all 0.2s ease-in-out;
}
<div class="box">
<div class="demo-field">
     <input name="dob" id="dob" type="text"  onfocus="(this.type='date')" onblur="if(!this.value) this.type='text'" placeholder="Date of Birth*" class="demo-input"  />
                                        <label for="dob" class="floating-label">Date of Birth*</label>
</div>
</div>
Md answered 27/7, 2022 at 6:15 Comment(0)
P
0

Using a placeholder in input="date" contradicts the control's logic. If you want your date control to have a custom logic try to find a solution in component library and get date control from there. For example, you may use bootstrap-datepicker it depends on input="type" to show the date https://bootstrap-datepicker.readthedocs.io/en/latest/

Other solution is flatpickr https://flatpickr.js.org/examples/

$("#txtDate").flatpickr({});
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/flatpickr/4.6.13/flatpickr.min.js"></script>

<div class="flatpickr">
    <input id="txtDate" type="text" placeholder="Select Date.." data-input> <!-- input is mandatory -->

    <a class="input-button" title="toggle" data-toggle>
        <i class="icon-calendar"></i>
    </a>

    <a class="input-button" title="clear" data-clear>
        <i class="icon-close"></i>
    </a>
</div>
Pentagon answered 30/8, 2022 at 8:50 Comment(0)
S
0

For React, you can do this.

const onDateFocus = (e) => (e.target.type = "date");
const onDateBlur = (e) => (e.target.type = "text");
.
.
.
  <input
    onFocus={onDateFocus}
    onBlur={onDateBlur}
    type="text"
    placeholder="Event Date"
  />
Specie answered 27/3, 2023 at 0:30 Comment(0)
P
0

jsx:

<input
    className={styles.input}
    data-error={error}
    data-value={!!inputProps.value}
    {...inputProps}
/>

styles.scss:

@media (min-width: (959px)) {
  .input[type='datetime-local']:not(&[data-value='true']):before {
    content: 'dd.mm.yyyy, --:--';
    width: 100%;
    color: #757575; // default placeholder color
  } 
  .input[type='time']:not(&[data-value='true']):before {
    content: '--:--';
    width: 100%;
    color: #757575; 
  }
  .input[type='date']:not(&[data-value='true']):before {
    content: 'dd.mm.yyyy';
    width: 100%;
    color: #757575;
  }
}
Pus answered 30/6, 2023 at 12:16 Comment(0)
D
0

To prevent oversizing onFocus and desired result u can do this

CSS

input[type="date"] {
 color: #ffffff;
 position: relative;
}
input[type="date"]::before {
 color: #98A2B3;
 content: attr(placeholder);
 position: absolute;
}
input[type="date"]:focus,
input[type="date"]:valid {
 color: #101828;
}
input[type="date"]:focus::before,
input[type="date"]:valid::before {
 content: "" !important;
}

HTML/JSX

<div className="flex flex-col mb-3 w-1/3 ">
    <label
      className="text-sm font-medium text-gray-700 pb-[6px]"
      htmlFor="date"
     >
      Date*
    </label>
    <input
     placeholder="Date"
     id="date"
     type="date"
     className={`${yourStyles}`}
     name="date"
     required
     //value={formData.date} React use only
     //onChange={handleInputChange} React use only
     />
</div>
Domett answered 7/2 at 5:50 Comment(0)
K
-1

Extension of Mumthezir's version that works better on iOS, based on Mathijs Segers' comment:

(Uses some AngularJS but hopefully you get the idea.)

<label style='position:relative'>
    <input type="date" 
           name="dateField" 
           onfocus="(this.type='date')"
           ng-focus="dateFocus=true" ng-blur="dateFocus=false" />
    <span ng-if='!dateFocus && !form.date' class='date-placeholder'>
        Enter date
    </span>
</label>

Because it's all wrapped in a label, clicking the span automatically focuses the input.

CSS:

.date-placeholder {
    display: inline-block;
    position: absolute;
    text-align: left;
    color: #aaa;
    background-color: white;
    cursor: text;
    /* Customize this stuff based on your styles */
    top: 4px;
    left: 4px;
    right: 4px;
    bottom: 4px;
    line-height: 32px;
    padding-left: 12px;
}
Kaciekacy answered 31/8, 2016 at 16:19 Comment(0)
M
-1

In React. My Case!

const [date, setDate] = useState(false)

then

<input type={`${date == true ? "date" : "text"}`} onFocus={() => setDate(true)} />
Morra answered 5/11, 2021 at 10:36 Comment(0)
L
-2

You could use the "value" attribute, for example:

<input type="date" value="Date" class="textbox-n" id="date"/>
Luciferous answered 7/4, 2014 at 12:6 Comment(1)
This is not correct. The value should have a format 'YYYY-MM-dd'. Otherwise, the value won't be displayed with warning message: The specified value 'Date' does not conform to the required format, 'yyyy-MM-dd'.Hightower

© 2022 - 2024 — McMap. All rights reserved.