WolfieeifloW WolfieeifloW - 1 year ago 99
jQuery Question

Select2 Select Function Shows Previous Value

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() {

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>

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..?

Answer Source

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.