Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple linked jQuery UI datepickers

I want to be able to link multiple pairs of jQuery UI datepicker instances so that the second one in each pair can't select a date earlier than the first. I'm following this example to get started.

Example:

<ul>
<li>
<input class="counter" name="counter" type="hidden" value="43"/>
<label>Start: </label><input name="start_43" id="start_43" size="10" />
<label>End: </label><input name="end_43" id="end_43" size="10" />
</li>

<li>
<input class="counter" name="counter" type="hidden" value="44"/>
<label>Start: </label><input name="start_44" id="start_44" size="10" />
<label>End: </label><input name="end_44" id="end_44" size="10" />
</li>
</ul>

I'm looping over the instances by finding the "counter" number:

$(document).ready(function() {
    var starts = $("input[name='counter']");
    var dates = new Array();
    starts.each(function(){
        var x = this.value;
        // http://jqueryui.com/demos/datepicker/#date-range
        dates[x] = $( "#start_"+x+", #end_"+x ).datepicker({
            onSelect: function( selectedDate ) {
            var option = this.id == "#start_"+x ? "minDate" : "maxDate",
            instance = $( this ).data( "datepicker" );
            date = $.datepicker.parseDate(
            instance.settings.dateFormat ||
            $.datepicker._defaults.dateFormat,
            selectedDate, instance.settings );
            dates[x].not( this ).datepicker( "option", option, date );
            }
        });
    });
});

This works to enable a datepicker on each input but it doesn't prevent the second instance from choosing a date before the first. In fact it requires that the second instance choose a date before the first. When selected, the second instance populates both inputs!

Can anyone see where I'm going wrong?

like image 223
oleonard Avatar asked Feb 24 '11 17:02

oleonard


1 Answers

I'm not 100% about what the parseDate is for, or why you're retrieving the instance from the datastore. However, I believe your primary problem is the this.id test. IDs never start with # in the actual DOM element.

onSelect: function(selectedDate) {
    var option = this.id.indexOf("start_") != -1 ? "minDate" : "maxDate";
    dates[i].not(this).datepicker("option", option, selectedDate);
}

The above should do it, or you could just take the hash out of your code probably (which I just did and seems to work fine). :]

like image 174
lsuarez Avatar answered Oct 17 '22 11:10

lsuarez