Javascript Question

Adding days by 7, when I choose a date?

I just want to ask here about on how to add dates in the "input" statement in the form? When I choose a date, it will increment the days by 7 and display it to the "input" statement the type is date. Here's my code.

just click this link, to view the image.

<title>Date Sample</title>
Start Date:<br/>
<input type="date" name="sdate" id="sdate"/>
End Date:<br/>
<input type="date" name="edate" id="edate"/>

Answer Source
  • Attach change listener

  • Use DateObj.getDate and DateObj.setDate methods to get required Date

  • Format the DateObj in YYYY-MM-DD to set the value

Note: I have added readonly attribute for end-date so that user can not edit that value.

$('#sdate').change(function() {
  if (this.value) {
    var d = new Date(this.value);
    var newDate = d.setDate(d.getDate() + 7);
    var dateObj = new Date(newDate);
    var day = ("0" + dateObj.getDate()).slice(-2);
    var month = ("0" + (dateObj.getMonth() + 1)).slice(-2);
    $('#edate').val(dateObj.getFullYear() + "-" + (month) + "-" + (day));
<script src=""></script>
  Start Date:
  <input type="date" name="sdate" id="sdate" />
  <br/>End Date:
  <input type="date" name="edate" id="edate" readonly />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download