Search code examples
javascriptjquerytwitter-bootstrapbootstrap-datetimepicker

Bootstrap datetimepicker enter key to fill initial date


Bootstrap datetimepicker as seen here: http://eonasdan.github.io/bootstrap-datetimepicker/

Specifically upon first showing, the enter key should hide the widget and place the current date into the input field. Here's some stuff I tried:

There's a dp.hide event which doesn't inject clues into the callback. So, you don't know how it got triggered.

$("#datePicker").on("dp.hide", function(e) {
    // e.notSquat
});

It's just not clear which DOM element of the datetimepicker is actually receiving an enter key internally. It's definitely not the input element:

// handler never gets called. css selector is correct
$("#datePicker input").keypress(function(e) {
   console.log(e.which);
});

I braved it, somewhat, by jumping into the code of datetimepicker.js itself: https://raw.githubusercontent.com/Eonasdan/bootstrap-datetimepicker/master/src/js/bootstrap-datetimepicker.js

There are clues, for example, line 2588, but my god there must be an easier way:

// line 2588
enter: function () {
        this.hide();
}

Any help is appreciated.


Solution

  • Figured it out, in case anyone finds this helpful. I overwrote the keyBinds.enter property when initializing the plugin.

    $("#datePicker").datetimepicker({
        keyBinds: {
            enter: function(){
                if(this.date() === null) {
                    this.date(moment());    // moment() is similar to new Date()
                }
                this.hide();
            }
        },
        useCurrent: false
    });