How to target multiple datepicker in a form?

I have a dynamic form with 4 datepicker inputs. How can I target these datepicker inputs to avoid past date after a first date is set?

Here is my code

$(function() {
    $( ".from" ).datepicker({
      onClose: function( selectedDate ) {
        $( ".to" ).datepicker( "option", "minDate", selectedDate );
      }
    });
    $( ".to" ).datepicker({
      onClose: function( selectedDate ) {
        $( ".from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });
  });

As you can see both inputs are affected when the user select one date. I want to target one each but as I mentioned my form is dynamic, the user can add 4.. 6.. 8 datepicker inputs.


If I've understood this correctly, you want N number of pairs of datepickers ("from" and "to"), which you need to tie together. Essentially, you need a way to go from a specific datepicker and identify only the one other datepicker that's tied to it. There are a number of ways you could do this, but I'd suggest wrapping your pairs in a containing HTML element (<div>) then doing the selectors relative to that. Something like this:

<div>
    <label class="required">Work from</label>
    <input type="text" class="form-control date-picker from input-append minDate" placeholder="mm/yyyy"/><br/>
    <label>Work until </label>
    <input type="text" class="form-control date-picker to input-append maxDate" placeholder="mm/yyyy"/>
</div>

<div>
    <label class="required">Study from</label>
    <input type="text" class="form-control date-picker from input-append minDate" placeholder="mm/yyyy"/><br/>
    <label>Study until </label>
    <input type="text" class="form-control date-picker to input-append maxDate" placeholder="mm/yyyy" />
</div>

Then you'd modify your jQuery code for the datepickers to look like this:

$(function() {
    $( ".from" ).datepicker({
        onClose: function( selectedDate ) {
            $(this).closest('div').find('.to').datepicker( "option", "minDate", selectedDate );
        }
    });
    $( ".to" ).datepicker({
        onClose: function( selectedDate ) {
            $(this).closest('div').find('.from').datepicker( "option", "maxDate", selectedDate );
        }
    });
});

The key change is this:

$(this).closest('div').find('.from')

In the function, this is the element of the datepicker that's just closed. .closest('div') traverses up the DOM tree until it finds the containing <div> element, then .find('.from') will find the one element with the class from inside it, which is the one element that's linked to that specific to element.