Is it possible to disable opening on key enter for select 2 (v 4.0.3)

房东的猫 提交于 2019-12-11 12:06:50

问题


Is it possible to disable opening on key enter for select 2 (v 4.0.3). I found somewhere that it can be done with options "openOnEnter: false", but it does not work for me.


回答1:


Unfortunately, no. At the time of version 4.0.3 at least.
It's hardcoded:

this.on('keypress', function (evt) {
  var key = evt.which;

  if (self.isOpen()) {
    // skipped
  } else {
    if (key === KEYS.ENTER || key === KEYS.SPACE ||
        (key === KEYS.DOWN && evt.altKey)) {
      self.open();

      evt.preventDefault();
    }
  }
});



回答2:


The behaviour to open the dropdown on Enter key press is hardcoded (as @Shrike said) and there is no option available to disable it (openOnEnter was used in v3, but was removed in v4).

I've found the following (dirty) solution, for Select2 v4 and single select, :

$(document).on('keydown', '.select2-selection', function (evt) {
    if (evt.which === 13) {
        $("#mySelect").select2('close');
    }
});

I catch the keydown event and call the select2 close method to immediately close the dropdown.

Tested in Chrome, Mozzila, Safari.

Fiddle: http://jsfiddle.net/j9t6sv8d/




回答3:


For anyone using select2.full.min.js, you may search for "a.open" and replace that part of the code with the one below:

this.options.get("disabled") ? b.preventDefault() : a.open()

This will inspect if the select2 element is disabled and prevent any further action.



来源:https://stackoverflow.com/questions/38460153/is-it-possible-to-disable-opening-on-key-enter-for-select-2-v-4-0-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!