Timobo Timobo - 7 months ago 1172
Javascript Question

Bootstrap-select on click get clicked value

I am using a jQuery plug-in: bootstrap-select.js my HTML is select(multiple) -> option. I would like to get the currently clicked on option value when a user selects or deselects the option.

Example: User selects Item 4 = console.log item 4. Then the user also selects Item 2 = console.log item 2. Currently i'm getting item 4, item 2... they are always in a array and not individual.

My end goal is to show and hide divs on the page depending on what the user has selected. There will be multiple select option fields.

HTML code:

<fieldset class="dreamT">

<select name="team" id="team" multiple class="dropdown selectpicker show-menu-arrow show-tick form-control" title="Pelaajat" data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
<optgroup>
<option value="item 1">Item 1</option>
<option value="item 2">Item 2</option>
<option value="item 3">Item 3</option>
<option value="item 4">Item 4</option>
<option value="item 5">Item 5</option>
<option disabled value="item 6">Item 6</option>
</optgroup>
</select>

</fieldset>


JS code:

$("select#team").on("change", function(value){
var This = $(this);
var selectedD = $(this).val();
console.log(selectedD);
});


Current output:
["item 1", "item 3", "item 4", "item 5"]


Plug-in site: bootstrap-select

Answer

As described in the bootstrap-select events you can use changed.bs.select event.

This event fires after the select's value has been changed. It passes through the followinf 4 arguments:

  • event
  • clickedIndex
  • newValue
  • oldValue

$(function () {
  $("#team").on("changed.bs.select", function(e, clickedIndex, newValue, oldValue) {
    var selectedD = $(this).find('option:eq(' + clickedIndex + ')').text()
    $('#log').text('selectedD: ' + selectedD + '  newValue: ' + newValue + ' oldValue: ' + oldValue);
  });
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css">
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>


<fieldset class="dreamT">

    <select name="team" id="team" multiple class="dropdown selectpicker show-menu-arrow show-tick form-control" title="Pelaajat" data-width="100%" data-size="auto" multiple data-selected-text-format="count > 2">
        <optgroup>
            <option value="item 1">Item 1</option>
            <option value="item 2">Item 2</option>
            <option value="item 3">Item 3</option>
            <option value="item 4">Item 4</option>
            <option value="item 5">Item 5</option>
            <option disabled value="item 6">Item 6</option>
        </optgroup>
    </select>
</fieldset>
<p id="log"></p>