Skip to content
Advertisement

Looping through selectpicker options

I am working with a selectpicker that contains optgroup and option elements. I would like to loop through the options and “select” all options that have a value starting with a certain string. For example, if I have the following:

<select id="sp" class="form-control selectpicker" data-live-search="true" data-live-search-style="startsWith" multiple>
  <optgroup label='Vegetables'>
    <option value='V.celery'>Celery</option>
    <option value='V.carrot'>Carrot</option>
    <option value='V.artichoke'>Artichoke</option>
  </optgroup>
  <optgroup label='Fruits'>
    <option value='F.cherry'>Cherry</option>
    <option value='F.apple'>Apple</option>
    <option value='F.papaya'>Papaya</option>
  </optgroup>
</select>

and some buttons “Vegetable” and “Fruit”, I would like all of the options that have values starting with “V.” to be selected when the user clicks the “Vegetable” button. How can I do this using the selectpicker ‘val’ option? Thanks!

Answer

function selector() {
  if (this.id === "vegBtn") document.querySelectorAll("optgroup[label='Vegetables'] option").forEach(elem => {
    if (elem.value.indexOf("V.") !== -1) elem.selected = !elem.selected;
  });
  else if (this.id === "fruBtn") document.querySelectorAll("optgroup[label='Fruits'] option").forEach(elem => {
    if (elem.value.indexOf("F.") !== -1) elem.selected = !elem.selected;
  });
}

document.getElementById("vegBtn").addEventListener("click", selector);
document.getElementById("fruBtn").addEventListener("click", selector);
<select id="sp" class="form-control selectpicker" data-live-search="true" data-live-search-style="startsWith" multiple>
  <optgroup label='Vegetables'>
    <option value='V.celery'>Celery</option>
    <option value='V.carrot'>Carrot</option>
    <option value='V.artichoke'>Artichoke</option>
  </optgroup>
  <optgroup label='Fruits'>
    <option value='F.cherry'>Cherry</option>
    <option value='F.apple'>Apple</option>
    <option value='F.papaya'>Papaya</option>
  </optgroup>
</select>
<button id="vegBtn">
 Vegetables
</button>
<button id="fruBtn">
 Fruits
</button>

I am not sure if you actually need to select for V or F in this situation but since that is what you asked for that is what I did. The two are not mutually exclusive so if you need that that requires more code.

Advertisement