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
2
Answers
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 changesYou should be able to toggle the property value between true and false. The method includes() returns a boolean and you can use that directly to set the boolean value of the multiple property on the select element.
Her is a vanilla JavaScript example: