Igor
Igor

Reputation: 381

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

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.

Upvotes: 1

Views: 4498

Answers (3)

NeedMeds
NeedMeds

Reputation: 41

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.

Upvotes: 0

andreivictor
andreivictor

Reputation: 8491

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/

Upvotes: 0

Shrike
Shrike

Reputation: 9500

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();
    }
  }
});

Upvotes: 1

Related Questions