uxsolutions / bootstrap-datepicker

A datepicker for twitter bootstrap (@twbs)
Apache License 2.0
12.66k stars 6.07k forks source link

Date not auto-selected in calendar if set via JavaScript #2483

Open SunnySanDiego opened 5 years ago

SunnySanDiego commented 5 years ago

Expected behaviour

If a datepicker is tied to a textbox and the textbox's value is set programmatically via JavaScript, when the datepicker is displayed it should have the set date automatically selected.

Actual behaviour

The date is not selected in datepicker.

Datepicker version used

1.6.4.

Example code

You can use the sandbox at https://uxsolutions.github.io/bootstrap-datepicker/?markup=input&format=&weekStart=&startDate=&endDate=&startView=0&minViewMode=0&maxViewMode=4&todayBtn=false&clearBtn=false&language=en&orientation=auto&multidate=&multidateSeparator=&keyboardNavigation=on&forceParse=on#sandbox

Go to the browser's Console window and type in the following:

$("#sandbox-container input.form-control").val('04/01/1999')

Now click on the textbox. The datepicker comes up, but the date in the textbox (04/01/1999) is not selected. There is no date selected.

BUT, if you type in that date into the textbox it is correctly selected.

Workaround

What I'm doing to work around this is the following... In the show event handler I call setDate and assign it the value in the textbox.

$(".dispatch-input").datepicker() .on('show', function () { $(this).datepicker('setDate', $(this).val()); });

SunnySanDiego commented 5 years ago

Actually, my prescribed workaround causes other issues. Namely, it prevents switching through the months in the calendar (clicking the < and > icons in the upper left and right corners).

What I had to do was extend the code to only set the date if the value reported by the datepicker doesn't match what's in its textbox.

ocarreterom commented 5 years ago

@SunnySanDiego you can update the value of the input before initialize the datepicker, or update the value after initialization with .datepicker('update', new Date()).