skip to Main Content

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


  1. 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);
    
    Login or Signup to reply.
  2. You 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:

    let element_text = "Test string including an a";
    
    document.forms.form01.ddl_account.multiple = !element_text.includes('a');
    <form name="form01">
      <select name="ddl_account" multiple>
        <option value="1">Option 1</option>
        <option value="2">Option 2</option>
      </select>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search