javascriptjqueryasp.net-mvcjquery-chosen

remove multiple attribute from chosen select jquery


I have a dropdown with chosen select plugin

@Html.DropDownListFor(x => x.ML.AccountID, Model.Accounts, new { id = "ddl_account", @class = "form-control form-control-sm chosen-select", @multiple = true })

Via jquery I want to make it single select or multi select based on some value

if (element_text.includes('a')) {
     $("#ddl_account").removeAttr("multiple").trigger('chosen:updated');
          }
else {
      $("#ddl_account").attr("multiple", true).trigger('chosen:updated');
          }

But it does not make any difference , if the element_text contain a , it will still be multiselect dropdown , although in inspect window, multiple attribute has been removed.

I also tried with prop

if (element_text.includes('a')) {
     $("#ddl_account").prop("multiple", false).trigger('chosen:updated');
  }
else {
     $("#ddl_account").prop("multiple", true).trigger('chosen:updated');
     }

How can I switch chosen select from single to multiple and vice versa ? Jquery version is 3.3.1


Solution

  • A workaround to do that is first destroy the existing Chosen instance, then Update the <select> element to be either single or multiple select based on your condition, and after that re-initialize Chosen to reflect the changes

    function toggleDropdown(element_text) {
        var $select = $("#ddl_account");
    
        $select.chosen('destroy');
    
        if (element_text.includes('a')) {
            $select.prop("multiple", false);
        } else {
            $select.prop("multiple", true);
        }
    
        $select.chosen({
            width: "100%",
            disable_search_threshold: 10
        });
    }
    
    toggleDropdown(someTextVariable);