1
votes

Description:

I'm using Select2 for dropdown, and i'm trying to disable selected option in list. I wrote the code given bellow but it is not working. Is there any mistake in this code?

Code:

$("#Users").change(function () {
            $(".select2-results .select2-results__option[aria-selected=true]").each(function () {
                $(this).attr("disabled","disabled");
            });
        });

Html:

<div class="form-group">
            @Html.Label("Send Mail To", new { @class = "control-label", @style= "position: absolute;margin-top:18px;" })
            <a id="clearSelectedUsers" class="pull-right btn btn-primary M-B10">Clear</a>
            @Html.DropDownListFor(m => m.Users, new SelectList(Model.Users, "Email", "Name"), "Select", new { multiple = "multiple", @class = "form-control" ,@disabled = "disabled" })
        </div>

Script:

var usersSelect2 = $("#Users").select2(); usersSelect2.val(toBeSelectedManagers).trigger("change");

2

2 Answers

2
votes

Try : 1. If you want to disable Full select element then

$("#Users").change(function () {
     $("#Users").prop("disabled", true);
   });

OR

$("#Users").change(function () {
     $(this).prop("disabled", true);
   });

2.if you want to disable selected option then do something like

$("#Users").change(function () {
    $.each(this.options, function (i, item) {
        if (item.selected) {
            $(item).prop("disabled", true); 
        }else {
            $(item).prop("disabled", false);
        }
    });
 });

You can find more information in this link.

0
votes

Select to dropdown one value selected next time can't select the same value:

$("#m_select2_2").select2().on("select2:select", function(e) {
  var selected_element = $(e.currentTarget);
  var select_val = selected_element.val();
  $.each(this.options, function(i, item) {
    if (item.selected) {
      $(item).prop("disabled", true);
    }
  });
  console.log(select_val);
  $('select').select2();
});