alexleonard
alexleonard

Reputation: 1314

jQuery Datepicker not getting minDate from this min attribute

Am I missing something wholly obvious here?

Html

<input class="datepicker" min="2014-10-22" name="start_date" type="text" value="2014-11-22" id="start_date">

Javascript

$(function() {
    $(".datepicker").datepicker({
        minDate: $(this).attr('min'),
        // minDate: '2014-10-22',
        dateFormat: 'yy-mm-dd',
        onSelect: function() {
            console.log($(this).attr('min'));
        }
    });
});

onSelect shows it's getting the min attribute correctly. But minDate seems to be ignoring it.

If I hardcode it then it works, but if I use minDate: $(this).attr('min'), then no minDate is set.

Upvotes: 2

Views: 1022

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388406

Because you are calling $(this).attr('min') inside the dom ready callback, where this refers to the document object not the input element.

If there is only one datepicker in the page you can change it to $('.datepicker').attr('min').

But if there are more than 1 then

$(function() {
  $(".datepicker").each(function() {
    $(this).datepicker({
      minDate: $(this).attr('min'),
      // minDate: '2014-10-22',
      dateFormat: 'yy-mm-dd',
      onSelect: function() {
        console.log($(this).attr('min'));
      }
    });
  })
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/redmond/jquery-ui.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.js"></script>

<input class="datepicker" min="2014-10-22" name="start_date" type="text" value="2014-11-22" id="start_date">
<input class="datepicker" min="2014-11-22" name="start_date" type="text" value="2014-11-22" id="end_date">

Upvotes: 4

Related Questions