Reputation: 1020
I am looking to change the date of the a datepicker id="datepicker_end"
based on the number of days entered into an input field id="totaldays"
.
The input field id="totaldays"
has 2 functions
1) It calculates the number of days between 2 datepickers (This works now, see JSFiddle http://jsfiddle.net/Deif/KLpq7/211/) - I want to keep this functionality.
2) If the user decides to enter the number of days directly into the input field then I want the 2nd datepicker id="datepicker_end"
to update based on the amount of days entered into the field.
The concept here is that the user can enter the amount of days they want or choose between 2 dates...
My JSFiddle is as follows http://jsfiddle.net/Deif/KLpq7/211/
I can't find any good examples so hope I am explaining it OK above.
Upvotes: 1
Views: 1169
Reputation: 40481
Do you mean something like this?
function days() {
var a = new Date($("#datepicker_start").val()),
b = new Date($("#datepicker_end").val()),
c = 24*60*60*1000,
diffDays = Math.round(Math.abs((a - b)/(c)));
$("#totaldays").val(diffDays);
}
function formatDate(_d){
var d = new Date(_d);
var curr_date = d.getDate();
if(curr_date < 10)
curr_date = "0" + curr_date;
var curr_month = d.getMonth() + 1; //Months are zero based
if(curr_month < 10)
curr_month = "0" + curr_month;
var curr_year = d.getFullYear();
return curr_month + '/' + curr_date + '/' + curr_year;
}
$('#totaldays').change(function(){
if($(this).val() != ''){
var days = $(this).val();
var start= new Date($("#datepicker_start").val());
var newStart = start.setDate(start.getDate() + parseInt(days));
$("#datepicker_end").val(formatDate(newStart));
}else{
$("#datepicker_end").val($("#datepicker_start").val());
}
});
$('.datepicker')
.datepicker({format: 'mm/dd/yyyy'})
.on('changeDate', function(ev){
days();
$(this).datepicker('hide').blur();
});
DEMO:
http://jsfiddle.net/dirtyd77/KLpq7/218/
Upvotes: 1