2
votes

I'm using Select2 as a searching dropdown, however when I select an item in the list it keeps showing the previous value.

I initialize the Select2 dropdown:

$(document).ready(function() {
  $(".ordersSelect").select2();
});

And then set all the options:

<select class="ordersSelect" style="width:75%;">
  <option value>Select a priority...</option>
  <option value="0">0</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
</select>

So let's say I select 1, my console from this code:

// when value is selected
$('.ordersSelect').on('select2:selecting', function(e) {
  var prioritySelection = $('.ordersSelect').select2('data')[0].text;
  console.log("DATA: " + prioritySelection);
});

Will show "DATA: Select a priority...". If I then select say '3', the console will show "DATA: 1".

It keeps on showing the value from the previous selection. When I change "select2:selecting" to "select2:selected" the console message just never comes up.

What am I doing wrong here..?

2

2 Answers

5
votes

First, you should definitely use select2:select.
select2:selecting is triggered before the result is selected..

$('select').on('select2:select', function (evt) {
  // Do something
});

Second, you can get the data object/value from the event itself. Check the evt.params.data property.

0
votes

Got it using:

$('.ordersSelect').select2().on("change", function(e) {
  var obj = $(".ordersSelect").select2("data");
  console.log("change val=" + obj[0].id);  // 0 or 1 on change
});

If anyone knows of a better way though, I am definitely up to hear it.