Rob Rob - 1 month ago 8
jQuery Question

bootstrap-datepicker multidate return all dates for selected days

http://bootstrap-datepicker.readthedocs.io/en/latest/markup.html

I have an inline datepicker with multidate set to true. I need users to select one or more days in the calendar which does work. How do I return the selected dates from my button? getDates as per the instructions does not return an array of the dates???



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>
<div class="datepicker" data-date-format="mm/dd/yyyy"></div>
<button type="button" class="btn btn-primary btn_save">Save</button>

<script>
$(document).ready(function () {
$('.datepicker').datepicker({
format: 'mm/dd/yyyy',
multidate: true,
daysOfWeekDisabled: [0, 6],
clearBtn: true,
todayHighlight: true,
daysOfWeekHighlighted: [1, 2, 3, 4, 5]
});

$('.datepicker').on("changeDate", function () {
var the_dates = $('.datepicker').datepicker('getDates');
//this does not work
console.log(the_dates)
});

$(document).on('click', ".btn_save", function (e) {
var the_dates = $('.datepicker').datepicker('getDates');
//this does not work
console.log(the_dates)
});

});

</script>




Answer

The class selector $('.datepicker') returns multiple elements, and you can only apply the function to one of them. In the following code, I changed it to $('.datepicker:first') to select the first element found.

$(document).ready(function () {
  $('.datepicker').datepicker({
    format: 'mm/dd/yyyy',
    multidate: true,
    daysOfWeekDisabled: [0, 6],
    clearBtn: true,
    todayHighlight: true,
    daysOfWeekHighlighted: [1, 2, 3, 4, 5]
  });
          
  $('.datepicker').on('changeDate', function(evt) {
    console.log(evt.date);
  });
          
  $('.btn').on('click', function() {
    var the_date = $('.datepicker:first').datepicker('getDates');
    console.log(the_date);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker.css" rel="stylesheet"/>

<div class="datepicker" data-date-format="mm/dd/yyyy"></div>
<button type="button" class="btn btn-primary btn_save">Save</button>

Comments