2013-02-11 189 views
1

我打算根據輸入字段id="totaldays"中輸入的天數更改日期選擇器id="datepicker_end"的日期。通過輸入字段中的天數更新Datepicker日期?

輸入字段id="totaldays"有2個功能

1)計算2個datepickers之間的天數(這個工作現在,看到的jsfiddle http://jsfiddle.net/Deif/KLpq7/211/) - 我想保留這個功能。

2)如果用戶決定在輸入字段中直接輸入天數,那麼我希望第二個日期選擇器id="datepicker_end"根據輸入字段的天數進行更新。

這裏的概念是,用戶可以輸入自己想要的天量或2個日期之間的選擇......

我的jsfiddle如下:http://jsfiddle.net/Deif/KLpq7/211/

我找不到任何好的例子,讓希望我在上面解釋它。

+0

這會幫助你的。確保在演示下面打開「查看源代碼」。 http://jqueryui.com/datepicker/#date-range – Dom 2013-02-11 18:02:20

+0

Dom,是的,這就是我現在在我的JSFIddle工作,我不知道如何編輯該字段來讓它更新日期 – Redwall 2013-02-11 18:12:51

回答

1

你的意思是這樣的嗎?

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/

+0

真棒大教堂,謝謝你很多隊友!這就像一個魅力!讓我的夜晚! – Redwall 2013-02-11 22:21:39