Search code examples
javascriptjquerytwitter-bootstraphtml-selectbootstrap-select

Get the current value in bootstrap-select


I used e.target.value to retrieve the current selected value from bootstrap-select but it returned the first selected value i.e. the alert kept displaying item 1, when item 1 and item 2 where selected even when item 2 was the most recently selected.

How can I get the value for the recent selection and how can I get how many options are selected?

   <select multiple class="selectpicker" multiple data-selected-text-format="count > 1">
    <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>

$('.selectpicker').change(function (e) {
    alert(e.target.value);
});

Solution

  • I think the answer may be easier to understand like this:

    $('#empid').on('click',function() {
      alert($(this).val());
      console.log($(this).val());
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
    <select id="empid" name="empname" multiple="multiple">
      <option value="0">item0</option>
      <option value="1">item1</option>
      <option value="2">item2</option>
      <option value="3">item3</option>
      <option value="4">item4</option>
    </select>
    <br />
    Hold CTRL / CMD for selecting multiple fields

    If you select "item1" and "item2" in the list, the output will be "1,2".