Search code examples
javascriptjquerybootstrap-selectpicker

Bootstrap select doesn't return clickedIndex on changed.bs.select


I'm using Bootstrap Select plugin.

<div class="form-group col-md-6">
    <select class="selectpicker form-control" id="veicoli" data-style="btn-transparent" data-title="Veicoli" data-selected-text-format="static" data-live-search="true" multiple>
        <option value="1">EA018YE</option>
        <option value="11">FM088KP</option>
        <option value="17">DT590LW</option>
        <option value="21">DB814RZ</option>
        <option value="33">DM408DG</option>
        <option value="40">EH942GJ</option>
    </select>
</div>

I select options programatically using:

$(document).ready(function() {
  $('#veicoli').selectpicker('val', data);
  $('#veicoli').selectpicker('refresh');
}

where data is an array:

["11", "33"]

The code above correctly select options in the bootstrap-select, but the fired event changed.bs.select, that I defined like this:

$(document).on('changed.bs.select', '#modale-dettagli #veicoli', function(e, clickedIndex, isSelected, previousValue) {
  console.log('e: ' + e);
  console.log('clickedIndex: ' + clickedIndex);
  console.log('isSelected: ' + isSelected);
  console.log('previousValue: ' + previousValue);
}

doesn't work as expected because clickedIndex is undefined

This is the output of the event above:

e: [object Object]
clickedIndex: undefined
isSelected: undefined
previousValue: undefined

Note that when the same options are clicked (with the mouse), the same event works correctly

EDIT: Just so you understand, the problem I'm experiencing now was a bug in an earlier version val() method doesn't fire changed.bs.select

EDIT 2: I've found that I can get the index of the selected option with this.selectedIndex (instead of using function parameter clickedIndex) and with some "code trick" the job can be done


Solution

  • clickedIndex is purposely only returned when a click event has been fired (when manually selecting an option). The documentation should probably be updated to reflect this, but it would be difficult to implement properly when using the val() method, as in the case of a multiple select, multiple values can be changed at once (so it would be difficult to determine which elements would be considered "clicked"). However, previousValue should be returned, and the fact that it isn't is a bug. That will be fixed in bootstrap-select v1.13.9, though (https://github.com/snapappointments/bootstrap-select/issues/2244).