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.

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

Answer
  • 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="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form>
  Start Date:
  <br/>
  <input type="date" name="sdate" id="sdate" />
  <br/>End Date:
  <br/>
  <input type="date" name="edate" id="edate" readonly />
</form>