[jquery] How to dynamically set bootstrap-datepicker's date value?

I am using bootstrap datepicker along with a line highchart.

I want the datepicker date to update when the chart is zoomed. Once that event triggers I update the values of the datepicker. The values update fine but when the calendar is clicked, the date on the popup calendar is still the old date.

Here is my datepicker:

<div class="input-append date pull-right" id="dpStartDate" data-date="@DateTime.Now.AddMonths(-1).ToString("dd/MM/yyyy")" data-date-format="dd/mm/yyyy">
    <input class="span2" id="startDateText" size="16" type="text" value="@DateTime.Now.AddMonths(-1).ToString("dd/MM/yyyy")" readonly="">
    <span class="add-on"><i class="icon-th"></i></span>
</div>

I have tried just updating the values using this code:

$('#dpStartDate').attr('data-date', startDate);
$('#startDateText').attr('value', startDate);

which updates the dates fine but doesn't set the calendar.

I've also tried triggering the onChange event, which also updates the dates but not the calendar:

$('#dpStartDate').trigger('changeDate', startDate);

$('#dpStartDate').datepicker()
    .on('show', function (ev) {
        ev.stopPropagation();
    })
    .on('changeDate', function (ev, date) {
        var startDate = new Date();
        if (date != undefined) {
            startDate = date;
            $('#dpStartDate').attr('data-date', startDate);
            $('#startDateText').attr('value', startDate);
        }
        else {
            startDate = ev.date;
            $('#dpStartDate').attr(startDate.getDate() + '/' + (startDate.getMonth() + 1) + '/' + startDate.getFullYear());
            $('#startDateText').attr(startDate.getDate() + '/' + (startDate.getMonth() + 1) + '/' + startDate.getFullYear());
        }
        $('#dpStartDate').datepicker('hide');
        ev.stopPropagation();
    });

Does anyone know if it's even possible to update the calendar like that?

Thanks

This question is related to jquery datepicker twitter-bootstrap

The answer is


You can use this simple method like :

qsFromDate = '2017-05-10';
$("#dtMinDate").datepicker("setDate", new Date(qsFromDate));
$('#dtMinDate').datepicker('update');

This works for me:

$('#dpStartDate').data("date", startDate);

If you refer to https://github.com/smalot/bootstrap-datetimepicker You need to set the date value by: $('#datetimepicker1').data('datetimepicker').setDate(new Date(value));


I had to do 'setValue' and 'update' in order to get it to work completely

$('#datepicker').datepicker('setValue', '2014-01-29').datepicker('update');

Use Code:

var startDate = "2019-03-12"; //Date Format YYYY-MM-DD

$('#datepicker').val(startDate).datepicker("update");

Explanation:

Datepicker(input field) Selector #datepicker.

Update input field.

Call datepicker with option update.


If you are using Bootstrap DatePicker version 4+

Note All functions are accessed via the data attribute e.g. $('#datetimepicker').data("DateTimePicker").FUNCTION()

To set the date value, your codes should be like

$("#datetimepicker").data("DateTimePicker").date(new Date());

For Bootstrap 4

If you are using input group in Bootstrap, you need to attach the new date to parent of the textbox, otherwise if you click on the calendar icon and click outside the date will be cleared.

<div class="input-group date" id="my-date-component">
   <input type="text" />
    <div class="input-group-append">
      <span class="input-group-text"><i class="fa fa-calendar"></i></span>
    </div>
</div>

You need to set date to input-group.date.

$('#my-date-component').datepicker("update", new Date("01/10/2014"));

Also check datepicker update method


$("#datepicker").datepicker("setDate", new Date);

This works for me

$(".datepicker").datepicker("update", new Date());

var startDate = new Date();

$('#dpStartDate').data({date: startDate}).datepicker('update').children("input").val(startDate);

another way

$('#dpStartDate').data({date: '2012-08-08'});
$('#dpStartDate').datepicker('update');
$('#dpStartDate').datepicker().children('input').val('2012-08-08');
  1. set the calendar date on property data-date
  2. update (required)
  3. set the input value (remember the input is child of datepicker).

this way you are setting the date to '2012-08-08'


On page load if you dont want to fire the changeDate event which I didnt

$('#calendarDatePicker').data("date", new Date());
$('#calendarDatePicker').datapicker();

$('#DateDepenseInput').val("2020-12-28")
the Format should be like Year-Month-Day
It worked well for me ...


Simple way like this (one line)

$('#startDateText').val(startDate).datepicker("update");

For datetimepickers use this this work for me

$('#lastdate1').data({date: '2016-07-05'});
$('#lastdate1').datetimepicker('update');
$('#lastdate1').datetimepicker().children('input').val('2016-07-05');

$('#datetimepicker1').data("DateTimePicker").date('01/11/2016 10:23 AM')

You can do also this way:

  $("#startDateText").datepicker({
                toValue: function (date, format, language) {
                    var d = new Date(date);
                    d.setDate(d.getDate());
                    return new Date(d);
                },
                autoclose: true
            });

http://bootstrap-datepicker.readthedocs.org/en/latest/options.html#format


This works for me,

$('#datepicker').datepicker("setValue", '01/10/2014' );
$('#datepicker').datepicker("setValue", new Date(2008,9,03));

This works perfectly for me. Simply put the following one.

$('.className').datepicker('setDate', 'now');

Better to use :

$("#datepicker").datepicker("setDate", new Date); 

instead of

$("#datepicker").datepicker("update", new Date);

If you use update, event changeDate isn't triggered.


@Imran answer works for textboxes

for applying the datepicker to a div use this:

$('#div_id').attr("data-date", '1 January 2017');
$('#div_id').datepicker("update");

comma-delim multiple dates:

$('#div_id').attr("data-date", '1 January 2017,2 January 2017,3 January 2017');

When using the methods of other answers, the configured options are lost, to correct it, you can use a global configuration:

$('.datepicker').datepicker();
$.fn.datepicker.defaults.format = 'dd/mm/yyyy';
$.fn.datepicker.defaults.startDate = "0";
$.fn.datepicker.defaults.language = "es";
$.fn.datepicker.defaults.autoclose = true;
$.fn.datepicker.defaults.todayHighlight = true;
$.fn.datepicker.defaults.todayBtn = true;
$.fn.datepicker.defaults.weekStart = 1;

Now you can use the update method without losing the options:

$(".datepicker").datepicker("update", new Date("30/11/2018"));

That really works.

Simple,

Easy to understand,

Single method to set and update plugin which worked for me.

$(".datepicker").datepicker("update", new Date());

Other ways to update

$('.datepicker').data({date: '2015-01-01'});
$('.datepicker').datepicker('update');

Dont forget to call update manually.


Try this code,

$(".endDate").datepicker({
    format: 'dd/mm/yyyy',
    autoclose: true
}).datepicker("update", "10/10/2016"); 

this will update date and apply format dd/mm/yyyy as well.


Please note that if you initiate a datepicker with a custom format, you can pass the simple string date as the second argument. This saves a few lines.

$('.selector').datepicker({
    format:'dd/mm/yyyy',
});

$('.selector').datepicker('update', '13/09/2019');

Try

$("#datepicker").datepicker('setDate','25-05-2020').datepicker('fill');

This works for me when setDate is not updating the date picker text field value on browser. " The additional .datepicker('fill');" repopulate the bootstrap datepicker for new date which is set by setDate method.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to datepicker

Angular-Material DateTime Picker Component? $(...).datepicker is not a function - JQuery - Bootstrap Uncaught TypeError: $(...).datepicker is not a function(anonymous function) Get date from input form within PHP Angular bootstrap datepicker date format does not format ng-model value jQuery Datepicker close datepicker after selected date bootstrap datepicker setDate format dd/mm/yyyy bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date Clear the value of bootstrap-datepicker Disable future dates after today in Jquery Ui Datepicker

Examples related to twitter-bootstrap

Bootstrap 4: responsive sidebar menu to top navbar CSS class for pointer cursor How to install popper.js with Bootstrap 4? Change arrow colors in Bootstraps carousel Search input with an icon Bootstrap 4 bootstrap 4 responsive utilities visible / hidden xs sm lg not working bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js Bootstrap 4 - Inline List? Bootstrap 4, how to make a col have a height of 100%? Bootstrap 4: Multilevel Dropdown Inside Navigation