Select2 - make it readonly (not disabled!) from js
Asked Answered
S

10

36

How can I dynamically make a select2 combobox read-only?

Here's what I've tried so far:

$('...').attr({'readonly': 'readonly'}).trigger('change.select2');
$('...').attr({'readonly': 'readonly'}).trigger('change');
$('...').select2().enable(false);
Stereobate answered 23/1, 2017 at 13:4 Comment(1)
.select2("readonly", true)Isia
B
21

See: http://select2.github.io/select2/

I did it with:

$("#modelname-fieldname").select2({disabled:'readonly'});

Where:

  • modelname-fieldname is as in: $form -> field($modelname, "fieldname") -> widget(Select2::classname(), [ ... ]);
  • readonly is true, false or a string readonly

Optionally you can change the cursor when hovering over the select2 field.

Bola answered 19/3, 2017 at 21:56 Comment(5)
This is not the correct answer any more. Select does not have a readonly property and this (.select2({disabled:readonly});) was removed from select2 as well. The way to do it is to disable the select (and use hidden input if you need to send the value)Hawn
The first codeblock helped me, I sat {disabled:'readonly'} and it worked ;)Modifier
This is not the correct answer any more. The question did not say for what version of select2 they were looking for a solution.Gosselin
This works perfectly with 4.0.7. $("#YourSelect").select2({ disabled:'readonly' }). Just make sure you have readonly as a string (thanks seniorpreacher).Gabey
This solution doesn't send data to formRotation
A
50

This is Solution for Latest select2 (Tested With 4.0.7) using css only

/*Select2 ReadOnly Start*/
    select[readonly].select2-hidden-accessible + .select2-container {
        pointer-events: none;
        touch-action: none;
    }

    select[readonly].select2-hidden-accessible + .select2-container .select2-selection {
        background: #eee;
        box-shadow: none;
    }

    select[readonly].select2-hidden-accessible + .select2-container .select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container .select2-selection__clear {
        display: none;
    }

/*Select2 ReadOnly End*/
Amourpropre answered 5/3, 2019 at 11:13 Comment(5)
This is beautiful!Vitta
This works on 4.0.13. I also had to use: element.attr("readonly",<true or false>);Jail
Nice! Thanks! I just wanted keep the arrow so I used : select[readonly].select2-hidden-accessible + .select2-container .select2-selection .select2-selection__rendered { opacity: .5; } select[readonly].select2-hidden-accessible + .select2-container .select2-selection__arrow{ opacity: .35; }Evaporate
This worked like a charm., You need to add attribute readonly to your normal selectRotation
And if someone wants to add a specific text color, try this: select[readonly].select2-hidden-accessible + .select2-container .select2-selection > .select2-selection__rendered{color: #A1A5B7 !important;}Uppercase
B
21

See: http://select2.github.io/select2/

I did it with:

$("#modelname-fieldname").select2({disabled:'readonly'});

Where:

  • modelname-fieldname is as in: $form -> field($modelname, "fieldname") -> widget(Select2::classname(), [ ... ]);
  • readonly is true, false or a string readonly

Optionally you can change the cursor when hovering over the select2 field.

Bola answered 19/3, 2017 at 21:56 Comment(5)
This is not the correct answer any more. Select does not have a readonly property and this (.select2({disabled:readonly});) was removed from select2 as well. The way to do it is to disable the select (and use hidden input if you need to send the value)Hawn
The first codeblock helped me, I sat {disabled:'readonly'} and it worked ;)Modifier
This is not the correct answer any more. The question did not say for what version of select2 they were looking for a solution.Gosselin
This works perfectly with 4.0.7. $("#YourSelect").select2({ disabled:'readonly' }). Just make sure you have readonly as a string (thanks seniorpreacher).Gabey
This solution doesn't send data to formRotation
R
14

Solution from Select2 - Issue #3387 - Readonly Support:

select[readonly].select2 + .select2-container {
  pointer-events: none;
  touch-action: none;

  .select2-selection {
    background: #eee;
    box-shadow: none;
  }

  .select2-selection__arrow,
  .select2-selection__clear {
    display: none;
  }
}

Edit: for versions > 4.07 - as commenters below correctly pointed out:

select[readonly].select2-hidden-accessible + .select2-container {
    pointer-events: none;
    touch-action: none;

    .select2-selection {
        background: #eee;
        box-shadow: none;
    }

    .select2-selection__arrow, select[readonly].select2-hidden-accessible + .select2-container .select2-selection__clear {
        display: none;
    }
}
Refit answered 10/8, 2017 at 9:14 Comment(2)
This doesn't work, you can still select the options. Also the closing tag for the first rule is way down at the end. The best solution that works for select2 is posted by @Ali JamalWalworth
The solution from @Ali Jamal is more practicalEggshell
R
2

The disabled attribute is not the good way, an HTML Element using this attribute prevents the data sending of the select when form is submit.

For a production mode, I had to find and write a solution... It works with the native readonly attribute of the select ! Here, applied to all select into the DOM having the Select2 mechanism :

$('select[data-select2-id]').on('select2:opening', function (e) {
    if( $(this).attr('readonly') == 'readonly') { // Check if select tag is readonly.
        //console.log( 'readonly, can't be open !' );
        e.preventDefault();
        $(this).select2('close'); 
        return false;
    }
    //else{ console.log( 'expandable/selectable' ); }
});

I've detailed it here wit a complete demo.

Rattray answered 18/6, 2021 at 9:52 Comment(1)
This solved my problem. Thanks.Falsetto
V
1

This works for me:

.select2("readonly", true);
.select2("readonly", false);
Vicious answered 11/3, 2020 at 13:21 Comment(1)
Maybe you meant .select2({"readonly": true}); But it still doesn't workUppercase
S
1

Here is a working example in jsfiddle

This is the Script used

    var $S1 = $("select[name=select1]");
    var $S2 = $("select[name=select2]");
  
  $('select').select2({
      width: '100%'
    });

    function readonly_select(objs, action) {
      if (action === true)
        objs.prepend('<div class="disabled-select"></div>');
      else
        $(".disabled-select", objs).remove();
    }
    $('#setreadonly').on('click', function() {
      //readonly_select($(".select2"), true);

      $S1.attr("readonly", "readonly");
   
        $S2.attr("readonly", "readonly");

    });
    $('#removereadonly').on('click', function() {
      //readonly_select($(".select2"), false);
    
        $S1.removeAttr('readonly');
    $S2.removeAttr('readonly');

    });
    $("#abc").on('submit', function() {
      alert($("#abc").serialize());
    });
Sebrinasebum answered 18/3, 2021 at 10:21 Comment(0)
R
0

you cannot make the select2 as readonly as per the new version

follow the link for the hack, its pure css

https://mcmap.net/q/419176/-select2-make-it-readonly-not-disabled-from-js

Rotation answered 14/9, 2022 at 13:48 Comment(0)
D
0

Here some basic logic for it, add readonly-select class to parent, so we can make CSS and jQuery logic for its children elements. please follow below code to make readonly select2 dropdown.

$('.readonly-select select').on('select2:opening', function (e) {
    if( $(this).attr('readonly') == 'readonly') {
        // Check if select tag is readonly
        e.preventDefault();
        $(this).select2('close');
        return false;
    }
});
.readonly-select .select2-container--default .select2-selection {
    background-color: #eee;
}
<div class="form-group readonly-select">
    <label>Contract Type</label>
    <select class="form-control select2" readonly>
    </select>
</div>
Dimerous answered 15/12, 2023 at 9:26 Comment(0)
I
-2

Below example works for me

$("#mySelect2Box").select2("readonly", true);
Interject answered 2/3, 2021 at 15:18 Comment(0)
R
-3

I'm working with Select 4.0 and this works well for me

$('#select2-element').on('select2:select', () => {
  $('#select2-element').data('select2').destroy();
  $('#select2-element').attr('readonly', true);
});
Responser answered 27/12, 2019 at 8:13 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.