Reputation: 2679
I would like to set the value of end date from numbers of days and start day selected in the form. I have tried this but it doesn't work.
$(document).on('change', "#startDate", function (e) {
e.preventDefault();
var nbDays = $("#nbDays").val();
var startDt = $("#startDate").val();
var endDt = $("#endDate").val();
$("#endDate").val(startDt + nbDays) ;
});
Upvotes: 0
Views: 1304
Reputation: 1736
Use the javascript Date object. This questions has been answered multiple places. Here's one example from a previous SO thread modified to your specs:
$(document).on('change', "#startDate", function (e) {
e.preventDefault();
var nbDays = $("#nbDays").val();
var startDt = $("#startDate").val();
//Depeneding on the what the startDt value is,
//you may have to use a different date constructor
var dat = new Date(startDt);
dat.setDate(dat.getDate() + nbDays)
//Depending on what the required output format is,
//you may want to grab the MM DD YY of date and format
//to your specs
$("#endDate").val(dat);
});
Here's the documentation on the javascript Date object.
Upvotes: 0
Reputation: 10090
jQuery is no big help handling dates. try moment.js to do the date manipulation!
moment.js can parse a string into a date object:
startDate = moment(startDate_string);
it can do addition:
endDate = startDate.add( nbdays, 'days');
and it can help with formatting the date as a string again (you might change this according to the date conventions of your language/locale)
endDate.format('MM/DD/YYYY');
See https://jsfiddle.net/bjelline/24440qqr/ for full example code.
Upvotes: 1