jquery:使用两个datepicker和两个字段(字段1,字段2 + 1天),如booking.com

时间:2013-01-08 16:13:41

标签: javascript jquery html jquery-ui-datepicker

你好吗?

我有两个带有两个字段的日期选择器

我希望当用户选择(发件人)时,第二个字段(TO)将在第二天。喜欢 booking.com

例如:当用户选择 01-01-2013时,直接第二个字段 TO 02-01-2013 (第二天) ) ......

查看此图片中的表格

enter image description here

这是jquery的代码:

$(function() {
$( "#from" ).datepicker({
    defaultDate: "+1D",
    changeMonth: true,
    numberOfMonths: 1,
    dateFormat:"dd-mm-yy",
    minDate: "+1D",
    showOn: "button",
    buttonImage: "http://keith-wood.name/img/calendar.gif",
    buttonImageOnly: true , 

    onSelect: function(dateText, inst){
        var d = dateFormat(new Date(dateText + 1), "DD/MM/YYYY");
        $("#to").val(d);
    }

});

这是我的HTML代码:

<form method="get" action="">
        <input type="submit" value="choose"/>
        <p><input type="text" name="from" id="from" />From<br/>
        <input type="text" name="to" id="to" />To
        </p>
</br>

    </form>

怎么做?

3 个答案:

答案 0 :(得分:3)

onSelect: function(dateText, inst){
    var d = $.datepicker.parseDate(inst.settings.dateFormat, dateText);
    d.setDate(d.getDate()+1);
    $("#to").val($.datepicker.formatDate(inst.settings.dateFormat, d));
}

答案 1 :(得分:2)

我为你创建了一个有效的JSFiddle:

http://jsfiddle.net/jirilmongeorge/f329k/26/

以下是javascript代码:

$(document).ready(function() {
    $( "#from" ).datepicker({
    defaultDate: "+1D",
    changeMonth: true,
    numberOfMonths: 1,
    dateFormat:"dd-mm-yy",
    minDate: "+1D",
    showOn: "button",
    buttonImage: "http://keith-wood.name/img/calendar.gif",
    buttonImageOnly: true , 
    onSelect: function(dateText, inst){
        var d = $.datepicker.parseDate(inst.settings.dateFormat, dateText);
        d.setDate(d.getDate()+1);
        $("#to").val($.datepicker.formatDate(inst.settings.dateFormat, d));
    }

   });

   $( "#to" ).datepicker({
        showOn: "button",
        buttonImage: "http://keith-wood.name/img/calendar.gif",
        buttonImageOnly: true,
        changeMonth: true,
        changeYear: true
    });

  $('#from').attr('readonly', true);
  $('#to').attr('readonly', true);
});

答案 2 :(得分:1)

您需要将dateText转换为正确的日期格式,然后加1并重新设置为#to值

var from = dateText.split("-");
var fDate = new Date(from[2], from[1] - 1, from[0]);

var newdate = new Date(fDate);
newdate.setDate(newdate.getDate() + 1);
$("#to").val(newdate.getDate() + "-" + newdate.getMonth() + "-" + newdate.getFullYear());