简体   繁体   中英

Set multiple options in Chosen from JS

I am using chosen.js for my multiselect dropdown. I want to set multiple true or false from JS, but I can't set it. How can I do that?

HTML :

<select name="test" id="id">
   <option value="">-- Select an option --</option>
   <option class="item" name="test" value="21" data-url="URL">A</option>
   <option class="item" name="test" value="22" data-url="URL">B</option>
   <option class="item" name="test" value="23" data-url="URL">C</option>
</select>

JS :

require([
  'jquery',
  'chosen'
], function($, chosen) {
  $('#id').chosen({
    width: '100%',
    multiple: true,
    //multiple: 'multiple', also tried this
    placeholder_text: "Select Options"
  });
})

Note: I don't want to set it in the HTML code directly.

UPDATE (Output) :

在此处输入图片说明

It's not possible to change the type of selection in the Chosen library itself. It's set using the multiple attribute on the HTML select element when the library is instantiated.

As you state that you don't want to, or cannot, amend the HTML:

Note that I don't want to set it in the HTML code directly.

Then you could instead set the multiple attribute in JS before you define the Chosen library. You can also remove the first 'Select an option' item too, as it's not relevant to a multiple select.

var $select = $('#id').attr('multiple', true);
$select.find('option:first').remove();
$select.chosen({
  width: '100%',
  placeholder_text: "Select Options"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM