AdrianoRR
AdrianoRR

Reputation: 1131

jquery UI - Adding date to selected date

It seems a simple thing but i'm unable to solve it and i really need this. How can i add a date to a selected date, through the SelectedDate event?

I need to perform a date range limit on 2 datepickers. Once the user set one datepicker the other needs to only allow date equals to the selected date of the first datepicker, plus one month.

Example: if i set '3 of march' on the first calendar, the second must allow only dates greater than '3 of april'.

So far by now i can only get the same selected date or the one i set through $('#dtpicker').datepicker( "setDate" , '+1m');. I tried the jquery-ui documentation example, but nothing.

Upvotes: 2

Views: 2076

Answers (2)

DarkAjax
DarkAjax

Reputation: 16223

This should do the trick for you:

var plus_one_month =  '';
var minus_one_month =  '';
$("#from").datepicker({
    beforeShow: function() {
        if($("#to").val() != '') { 
            minus_one_month =  new Date($("#to").val());
            minus_one_month.setMonth(minus_one_month.getMonth() - 1);
        } else {
            minus_one_month =  '';
        }
        return {
            minDate: minus_one_month,
            maxDate: new Date($("#to").val())
        }
    }
});

$("#to").datepicker({
    beforeShow: function() {
        if($("#from").val() != '') { 
            plus_one_month =  new Date($("#from").val());
            plus_one_month.setMonth(plus_one_month.getMonth() + 1);
        } else {
            plus_one_month =  '';
        }
        return {
            minDate: new Date($("#from").val()),
            maxDate: plus_one_month
        }
    }
});

As you can see here.

Upvotes: 5

jb10210
jb10210

Reputation: 1176

I have implemented similar functionality on two datepickers.

function handleDateChange() {
    var dateStart = $('#datepicker-startdate').datepicker("getDate"), 
        dateEnd = $('#datepicker-enddate').datepicker("getDate");
    if (dateStart !== null) {
        dateStart.setDate(dateStart.getDate() + 1);
        $('#datepicker-enddate').datepicker('option', 'minDate', dateStart);
    }
    if (dateEnd !== null) {
        dateEnd.setDate(dateEnd.getDate() - 1);
        $('#datepicker-enddate').datepicker('option', 'maxDate', dateEnd);
    }
 }

Use this method in the onSelect handler of your datepickers (as init option):

$(/*your datepicker selector*/).datepicker({
    // ... other init options
    onSelect : function(dateText, inst) {handleDateChange();}
});

I think this is similar to what you need, if not then it should definitely get you on the right track.

Upvotes: 1

Related Questions