Sideshow
Sideshow

Reputation: 1351

html5 datepicker set min and max values

I am wantinr to use the html5 date function to allow the user to select a date. I am aware of the (still) limited browser support for this function and have utilised a fallback for non supported browsers using the JQuery datepicker plugin - this works fine.

The jQuery datepicker allows the setting of min and max dates....

$('#amender').datepicker({ dateFormat: "dd/mm/yy", minDate: 0, maxDate: "+2M"});

I understand that the html5 version uses the min and max elements to set these yet I have been unable to find the correct formatting to represent the above - all the examples I have found use specific dates in these fields.

Upvotes: 2

Views: 5595

Answers (1)

Lemonade
Lemonade

Reputation: 503

I flddled around and found the following solution, that takes the current date, fixes the number of digits for day/month < 10 and creates a datepicker with the desired range.

// get current date
var d = new Date();
// add 2 month and auto adjust date
d.setMonth(d.getMonth()+2);

// make 2 digits out of 1
var day = d.getDate();
if(day<10)
day = "0"+day;

var month = d.getMonth()+1;
if(month<10)
month = "0"+month;

// same for current (to be the min later)
var cDay = d.getDate();
if(cDay<10)
cDay = "0"+cDay;

var cMonth = d.getMonth()+1;
if(cMonth<10)
cMonth = "0"+cMonth;

var curEntry = d.getYear()+1900+"-"+cMonth+"-"+cDay;
var dateEntry = d.getYear()+1900+"-"+month+"-"+day;

// create the datepicker with appropriate min and max
document.write("<input type='date' min='"+curEntry+"' max='"+dateEntry+"'>");

Upvotes: 3

Related Questions