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
<html>
<body>
<select>
<option value="6">6 Months</option>
<option value="12">1 Year</option>
</select>
<input type="date" name="Sdate" id="Sdate">
<input type="date" name="edate" id="edate">
</body>
</html>
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
function setDate() {
let d = new Date(document.getElementById("sDate").value)
let mon = +document.getElementById("mon").value;
d.setMonth(d.getMonth()+mon)
document.getElementById("eDate").valueAsDate = d;
}
document.getElementById("sDate").addEventListener("change",setDate)
document.getElementById("mon").addEventListener("change",setDate)<select id="mon"> <option value="6">6 Months</option> <option value="12">1 Year</option> </select> <input type="date" name="Sdate" id="sDate"> <input type="date" name="edate" id="eDate">