I have two datepickers and one combobox in HTML. The combobox contain 2 values (6 months and 1 year). If I select 6 months from the combobox the second datepicker should show the date after 6 months from the first datepickers date.
I need code for this using JavaScript only not in jQuery.
My code is
JavaScript
x
11
11
1
<html>
2
<body>
3
<select>
4
<option value="6">6 Months</option>
5
<option value="12">1 Year</option>
6
</select>
7
<input type="date" name="Sdate" id="Sdate">
8
<input type="date" name="edate" id="edate">
9
</body>
10
</html>
11
Advertisement
Answer
I get the date from the start and add the number of months – then set the second datepicker using valueAsDate
I then add this function to both start date and month selector
Vanilla JavaScript
JavaScript
1
9
1
function setDate() {
2
let d = new Date(document.getElementById("sDate").value)
3
let mon = +document.getElementById("mon").value;
4
d.setMonth(d.getMonth()+mon)
5
document.getElementById("eDate").valueAsDate = d;
6
}
7
8
document.getElementById("sDate").addEventListener("change",setDate)
9
document.getElementById("mon").addEventListener("change",setDate)
JavaScript
1
6
1
<select id="mon">
2
<option value="6">6 Months</option>
3
<option value="12">1 Year</option>
4
</select>
5
<input type="date" name="Sdate" id="sDate">
6
<input type="date" name="edate" id="eDate">