Search code examples
javascriptjquerybootstrap-datepickeronfocus

Bootstrap datepicker: Focus without opening


I'm using a bootstrap datepicker and jQuery validate. I have jquery validate set to focus on the input when the field is empty & required.

With bootstrap datepicker however, the focus event causes the calendar to open. Which is not ideal in my situation. I'm wondering if there is a way to focus, but pass through a preventDefault or something like that?

I made a jsfiddle. Basically, is it possible to click the button to focus on the element, but not have the calendar open? https://jsfiddle.net/a2gkpxuh/ The primary purpose of the focus is to scroll the page so the user can see the required element.

$("#myButton").click(function () {
   //Some code to prevent default here?  Possibly disable datepicker before .focus event
   $("#myDatePicker").focus();
});

I guess one possible solution would be to disable the datepicker, then do my jQuery.validate(), then re-enable the datepicker. I feel like there's a better way though...

FYI Here is a similar question: Set focus on Jquery datepicker on datepicker close, without opening datepicker


Solution

  • You could just hide the datepicker after the focus:

    $("#myButton").click(function () {
        $("#myDatePicker").focus();
      $("#myDatePicker").datepicker('hide');
    });