Ankita Patel
Ankita Patel

Reputation: 251

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) :

enter image description here

Upvotes: 1

Views: 1491

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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"
});

Upvotes: 4

Related Questions