1) cache the elements.
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
2) The value of d1
and d2
are string
data type. So split them and parse it to date format as below
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
Here the year is incremented by 1, based on the value in d1
.
4) Again parse it back to string format (YYYY-MM-DD)
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
5) Set this as value for max
attribute for d2
d2.setAttribute("max", maxi);
Finally add the below method to onblur
event of d1
.
function setMaxDate() {
var d1 = document.getElementById('date1');
var d2 = document.getElementById('date2');
var t = d1.value.split("-");
var date = new Date(parseInt(t[0], 10) + 1, parseInt(t[1], 10), t[2]);
var maxi = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
d2.setAttribute("max", maxi);
}
JSFiddle