Update bootstrap 3 datepicker options dynamically?

Ivan Juarez picture Ivan Juarez · May 30, 2017 · Viewed 11.3k times · Source

This datepicker it is already created with other default options, but I need to update it with the following new options and it does not seem to work:

// new options
var new_options = {
    format: 'dd/mm/yyyy',
    autoclose: true,
    language: 'es'
}

// update values
$("#fecha_periodo").datepicker("update", new_options );

I would also like to update other options like daysOfWeekDisabled, viewMode and so on.

Answer

VincenzoC picture VincenzoC · May 30, 2017

Unfortunately, there is no API to change options dinamically, all availables methods are listed here (you can use setDaysOfWeekDisabled to set dinamically days of week disabled).

You can use destroy method to destroy datepicker instance and build it again with the new options.

Here a live example:

$('#datepicker').datepicker();

$('#btnChange').click(function(){
  var new_options = {
    format: 'dd/mm/yyyy',
    autoclose: true,
    language: 'es'
  }
  // Save value
  var value = $('#datepicker').datepicker('getDates');
  // Destroy previous datepicker
  $('#datepicker').datepicker('destroy');
  // Re-int with new options
  $('#datepicker').datepicker(new_options);
  // Set previous value
  $('#datepicker').datepicker('setDates', value);
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet"/>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.6.4/locales/bootstrap-datepicker.es.min.js"></script>

<input type="text" class="form-control" id="datepicker">

<button id="btnChange" class="btn btn-primary">Change option</button>