Reputation: 3
I always get value from the previous value instead of selected value from select2.
Here is my code:
$('.itemclass').on("select2:selecting", function (e) {
alert($('.itemclass').select2().val());
});
Here is the Selection (I used select2). My last selection is 'ADDUAT_AE' and I select new item which is 'AMCAT_0807'.
But the problem is I always get the previous selected item.
HTML Code:
<div class="input-group">
<select class="btn btn-default form-control itemclass" style="width: 100%;">
<option>ADDUAT_AE</option>
<option>AMC_AB</option>
<option>AMCAT_0807</option>
<option>CSQT_AC</option>
<option>ENK_EKA</option>
<option>FIG6_B0905</option>
</select>
<div class="input-group-btn">
Thanks in advance
Upvotes: 0
Views: 5030
Reputation: 11
Replace select2:selecting with select2:close.
$('.itemclass').on("select2:close", function (e) {
alert($('.itemclass').select2().val());
});
Upvotes: 0
Reputation: 854
$(".itemclass").select2();
$('.itemclass').on("select2:select", function (e) {
alert($('.itemclass').select2().val());
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<div class="input-group">
<select class="btn btn-default form-control itemclass" style="width: 100%;">
<option>ADDUAT_AE</option>
<option>AMC_AB</option>
<option>AMCAT_0807</option>
<option>CSQT_AC</option>
<option>ENK_EKA</option>
<option>FIG6_B0905</option>
</select>
<div class="input-group-btn">
select2:selecting method is Triggered before a result is selected.that's why value is not updated at that time.for more detail see official document https://select2.org/programmatic-control/events you can use select2:select or select2:close
Upvotes: 1
Reputation: 3005
According to the documentation here: https://select2.org/programmatic-control/events
select2:selecting - Triggered before a result is selected. This event can be prevented.
This means it happens before actually doing the select. So, if you get the value on :selecting
you get the value before the select.
You need: select2:select
which is Triggered whenever a result is selected.
So your code will be:
$('.itemclass').on("select2:select", function (e) {
alert($('.itemclass').select2().val());
});
Another option would be the one found in this answer which does not use the select2 events: select2 alert selected option when selecting the value
Upvotes: 0
Reputation: 24
alert($('.itemclass').select2().val())
This code block gives you the selected value do you need focused value?
Upvotes: 0