Vince
Vince

Reputation: 13

How to set a default value for a type=date input that works with html 5 browsers and with older browsers

I want to set the default value of a date input, for instance : 25/12/2015 (european date format).

If the browser is html 5 compatible and I use type="date" in the input field, I have to add value="2015-12-15", but if the browser is NOT html 5 compatible, I have to set value="25/12/2015".

How can I make my code (php and js) compatible with both kinds of browsers (html 5 compatible or not) ?

solution #1 : I don't use html 5 "type=date". Not sufficient since I'd like to use the browser datepicker whenever it's possible (specially with smartphones).

solution #2 : I check if the browser supports HTML5, and set the value accordingly, but it's a bit heavy...

Anybody has a smarter solution ?

Upvotes: 1

Views: 3035

Answers (2)

Vince
Vince

Reputation: 13

I tried to implement adeneo solution so as it works "automaticaly" for all of the type="date" inputs of a page.

$date="25/12/2015";
echo "<input name=\"date_number_1\" type=\"date\" value=\"$date\">";

window.onload = manage_date_input();

function manage_date_input(){
   var t_input = document.getElementById('mypage').getElementsByTagName('input');
   for(var i=0; i<t_input.length; i++)
   if(t_input[i].type === 'date'){
      var val=t_input[i].value;
      t_input[i].value=val.substring(6,4)+'-'+val.substring(3,2)+'-'+val.substring(0,2);
}

But it doesn't work because it seems that on the onload event, the value is already refused by the input due to the wrong date format...

So I had to do "the contrary" :

$date="2015-12-25";
echo "<input name=\"date_number_1\" type=\"date\" value=\"$date\">";

function manage_date_input(){
 var t_input = document.getElementById('mypage').getElementsByTagName('input');
 for(var i=0; i<t_input.length; i++)
 if((t_input[i].name.substring(0,4)=='date')&&(t_input[i].type != 'date')&&t_input[i].value){
   var val=t_input[i].value;
   t_input[i].value=val.substring(8)+'/'+val.substring(5,7)+'/'+val.substring(0,4);
 }
}

It works, seamlessly with new html 5 browsers and old browser that doesn't handle type=date, but I have to name all the date inputs "date_something" and I'm sure one can do better ;-)

Upvotes: 0

adeneo
adeneo

Reputation: 318352

Should be straight forward really

var input = document.getElementById('#id_of_your_date_input'); // <input type="date">

if ( input.type === 'date' ) {
    input.value = "2015-12-15";
} else {
    input.value = "25/12/2015";
}

The inputs type will only be date if that's supported, in older browsers the type will fall back to text

Upvotes: 2

Related Questions