'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!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source