jQuery UI Datepicker Add Days

2019-02-14 23:53发布

I'm attempting to create something of range system for booking rooms on a hotel website and I'm using jQuery UI Datepicker to allow the user to select their check in date. What I then want to do is create another field that's simple "Number of Nights" and have jQuery Datepicker take the check in date, add the number of nights, and set the resulting date as the value of a hidden input (in the correct date format). It would look something like this:

<input type="text" name="arrivalDate" class="datepicker">
<input type="text" name="numOfNights">
<input type="hidden" name="departureDate" value="arrivalDate + number of nights">

Is this possible? Thanks in advance.

(Note: The database I'll be "get"-ing from with this form is a little temperamental and I don't have access to it beyond just a few query-able values.)

3条回答
贪生不怕死
2楼-- · 2019-02-15 00:34

The above can be achieved by following code -

 $('input[name="arrivalDate"]').datepicker({

     //your other configurations.     

     onSelect: function(){
     var start = $('input[name="arrivalDate"]').val();
     var nights = $('input[name="numOfNights"]').val();
     var date = new Date(start);
     var d = date.getDate();
     var m = date.getMonth();
     var y = date.getFullYear();
     var edate= new Date(y, m, d+nights);
     $('input[name="departureDate"]').val(edate);
    }
 });
查看更多
迷人小祖宗
3楼-- · 2019-02-15 00:37

You can update the value of the hidden field in the onSelect events for the arrivalDate datepicker.

$('#arrivalDate').datepicker({
    onSelect: function(dateStr) {
        var nights = parseInt($('#numOfNights').val());
        var depart = $.datepicker.parseDate('mm/dd/yy', dateStr);
        depart.setDate(depart.getDate() + nights);
        $('#departureDate').val(depart);
     }
});

You'll have to also update the departureDate field from the change event of the numOfNights field.

$('#numOfNights').change(function() {
        var nights = parseInt($('#numOfNights').val());
        var depart = $.datepicker.parseDate('mm/dd/yy', $('#arrivalDate').val());
        depart.setDate(depart.getDate() + nights);
        $('#departureDate').val(depart);
});

Try it out here: http://jsfiddle.net/JKGvD/

You'd probably want to make that a function and also use it to initialize the departureDate if your arrivalDate has an initial value.

查看更多
放荡不羁爱自由
4楼-- · 2019-02-15 00:42

Use the setDate function.

setDate

Signature: .datepicker( "setDate" , date )

Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

查看更多
登录 后发表回答