How to properly disable a select2 element?

I currently use one line of code to disable a select/select2 element:

$("#example1").prop("disabled", true);

The box or the element itself is greyed out visually. If I only use my mouse to just click on it, it will not open again. However if I click on the element and press spacebar, the list of options still appear and I am able to change the selection. So I am curious right now if there is a method to prevent users from making changes to a greyed out or disabled box?

here is a jsbin.

This seems to be a bug (see below). It appears that the keyboard handling code does not respect the disabled attribute/property on the <select> element. I confirmed that even setting the disabled attribute directly in the <select> HTML tag results in the behavior you demonstrated.

Select2 GitHub issue #4695 seems to cover this bug, so it’s already a known issue (since January 2017).

You can hack a solution by adding a handler for the select2:opening event that immediately cancels the event (by returning false) if the disabled property is set on the <select> element:

  $('#example1').on('select2:opening', function(evt) {
    return !this.disabled;
  });
1 Like