I have a form with three fields, "start_date", "days", "end_date". I would like to get the end date by adding days to the start date.
My jQuery code is:
$("#days").change(function(){
var start_date = new Date($("#start_date").attr('value'));
var days = parseInt($("#days").attr('value'))-1;
var end_date = new Date(start_date);
end_date.setDate(start_date.getDate() + days);
$("#end_date").val(end_date.getFullYear() + '-' + ("0" + (end_date.getMonth() + 1)).slice(-2) + '-' + ("0" + end_date.getDate()).slice(-2));
});
In the "end_date" field I get "NaN-aN-aN".
What am I doing wrong?
NaN stands for Not a Number
- This means that the users input is invalid.
You could check to see if the input is valid by using if(!isNaN(date.getTime())){
Some code to get you started:
;(function($, window, document, undefined){
$("#days").on("change", function(){
var date = new Date($("#start_date").val()),
days = parseInt($("#days").val(), 10);
if(!isNaN(date.getTime())){
date.setDate(date.getDate() + days);
$("#end_date").val(date.toInputFormat());
} else {
alert("Invalid Date");
}
});
//From: http://stackoverflow.com/questions/3066586/get-string-in-yyyymmdd-format-from-js-date-object
Date.prototype.toInputFormat = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
};
})(jQuery, this, document);
http://jsfiddle.net/MCzJ6/1
Hope this helps.
W
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With