Disable enter key in JQuery ui datepicker

前端 未结 5 1953
暗喜
暗喜 2020-12-11 04:58

There seems to be a bug with JQuery UI datepicker, when user manually enters a date, and hits enter, the datepicker closes but focus stays on the field and therefor calendar

相关标签:
5条回答
  • 2020-12-11 05:22

    I initially had problems applying your solution. I thought it worthwhile to post my larger snippet that gives a little more context.

    if (!Modernizr.inputtypes.date) {
        //use modernizer to weed out browsers that already have a timepicker 
        //http://stackoverflow.com/questions/11297827/html5-date-input-type-interfering-with-jquery-datepicker
    
        $("input[data-val-date]")
                        .bind('keydown', function (event) {  // BEGIN APPLYING NinaNa's S.O. ANSWER
                        if (event.which == 13) {
                            var e = jQuery.Event("keydown");
                            e.which = 9;//tab 
                            e.keyCode = 9;
                            $(this).trigger(e);
                            return false;
                        }
        }).datepicker({ dateFormat: 'mm/dd/yy' }); //THEN APPLY JQUERY UI FUNCTIONALITY
    
    
    }
    
    0 讨论(0)
  • 2020-12-11 05:32

    Use e.stopImmediatePropagation(), and make sure the keydown binding happens before calling datepicker().

      $('input').on('keydown', function(e) {
          if (e.which == 13)
              e.stopImmediatePropagation();
      }).datepicker();
    

    Credit

    0 讨论(0)
  • 2020-12-11 05:34

    Solved by adding a blur() event to the onClose method of the datepicker.

    0 讨论(0)
  • 2020-12-11 05:38

    The simplest approach is to instantiate the datepicker on the <input> like you normally would, but then get rid of the focus handler ourselves and replace it with a click handler.

    0 讨论(0)
  • 2020-12-11 05:41

    Try this

    $(document).keydown(keyDownHandler); // use appropriate selector for the keydown handler
    
    function keyDownHandler(e) {
        if(e.keyCode === 13) {
            e.stopPropagation();
            e.preventDefault();
    
            return false;
        }
    }
    

    e.stopPropagation prevents bubbling, e.preventDefault prevents default behaviour and returning false does too, I think.

    You should have a look what works best: keyUp, keyDown or keyPress.

    0 讨论(0)
提交回复
热议问题