select2: JQuery Select2 cannot enable after disable

I am using Select2 version 4.0.5.

My Code

php

<select class="form-control customer" disabled>
    <option value=""></option>
    @foreach($customer as $c)
        <option value="{{ $c->id }}">{{ $c->user->name }}</option>
    @endforeach
</select>

jquery

$(function() {
    $('.customer').select2({
        placeholder: "Choose Customer"
    });
    $('.customer').val(0).trigger('change.select2');
});

$('.action_add').on('click', function() {
    $('.customer').select2('enable', false);
});

$('.action_delete').on('click', function() {
    if(IsEmptyRow()) {
        alert('test');
        $('.customer').select2('enable', true);
    }
});

Explanation

Enable false is working to make the select2 disable. When I want to enable it back, using enable true cannot make it enable back. The alert test inside the if code block is working.

System Details

Mac OS 10.13.5 PHP 7.0.9 Laravel 5.5

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Comments: 20 (5 by maintainers)

Most upvoted comments

The $('.customer').select2().prop("disabled", true); still cannot enable it back.

Hello @kevin-brown , The dropdown gets disabled , but once the dropdown is disabled, on clicking of space or enter keys , the drop down opens and we can change the values . Is there any other way we could disable it ? Have been trying out all the options here and have also looked into stackoverflow .

Here’s a jsfiddle showing that prop('disabled', true/false) works as expected. This is the recommended way to do this.

https://jsfiddle.net/3f1bs2j7/

select2('enable') and select2('disable') are explicitly deprecated and are not recommended. I’ve gone and updated that Stack Overflow answer to reflect this change in the new version.

I had this issue too using the latest version (4.0.7). Disabling options with the following jQuery (on version 2.2.4) did not cause the widget to update (whereas, it did in 4.0.3, but could not be re-enabled).

$(this).find("select :not(option:selected)").prop("disabled",true);

Calling the Select2 initialiser again worked around both issues.

$(this).find("select").select2();

Stumbled upon the same issue, the fix that works for me is sending the value as an array: $('.customer').select2('enable', [false]) or $('.customer').select2('enable', [true])