Search code examples
javascriptjquerytwitter-bootstrapmulti-selectbootstrap-multiselect

Get selected index/indices in a bootstrap multiselect control element


I have a Bootstrap multiselect element which looks something like this:

enter image description here

I know how I can retrieve the value of the selected item, i.e. $('#multiselectElement').val();

This code could return e.g. ['Cheese', 'Mozzarella,', 'Onions']

The things is, I need not the item values, but their INDICES. My intention is to return [0, 2, 5] instead of ['Cheese', 'Mozzarella,', 'Onions'].

How can I do that?


Solution

  • Make your values the indexes...

    <select id="example-single">
        <option value="0">Cheese</option>
        <option value="1">Tomato</option>
        <option value="2">Mozzarella</option>
        <option value="3">Onions</option>
        ...
    </select>
    

    Select the option elements...

    $('#multiselectElement option:selected').map(function(a, item){return item.value;});