marcosh
marcosh

Reputation: 9008

set datepicker mindate with jquery

I am trying to set a minDate in a jquery-ui datepicker. The date is retrieved using jquery from a data attribure of a parent node.

<p data-min-date="2015-03-10">Date:
    <input id="datepicker" type="text">
</p>
<script>
    $("#datepicker").datepicker({
        minDate: $(this).closest('p').data('minDate'),
        dateFormat: 'yy-mm-dd'
    });
</script>

You can check this fiddle to see that the minDate is not considered by the datepicker.

Can you spot what I'm doing wrong?

Upvotes: 1

Views: 602

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

The issue is because $(this) in the scope of the datepicker intialiser does not equal the element which was selected. To do what you require, you need to wrap the datepicker() call in an each() and iterate over every element of the selector:

$("#datepicker").each(function() {
    $(this).datepicker({
        minDate: $(this).closest('p').data('minDate'),
        dateFormat: 'yy-mm-dd'
    });
});

Updated fiddle

Alternatively, if the datpicker will only ever be created on a single element, you can select it directly for the minDate property:

$("#datepicker").datepicker({
    minDate: $("#datepicker").closest('p').data('minDate'),
    dateFormat: 'yy-mm-dd'
});

Updated fiddle

Upvotes: 2

Related Questions