Reputation: 1579
In select2 how can I alert the option being selected for a multiple select?
This is my code for trigger when select2 option is being selected:
<script>
$("#list").select2();
$('#list').on("select2-selecting", function(e) {
alert(this.value);
});
</script>
This will only alert the already selected value. Not the option that I am selecting.
I can't also do this:
var test = $('#list').val();
alert(test);
Since it will only alert the already selected options as well.
What I want is to alert the option that is still being selected. So if you click the drop-down and select an option it will alert the value of that option.
The first option is selected by default. Sorry I forgot to mention this
Upvotes: 3
Views: 6547
Reputation: 16595
Get selected value
with:
$(this).find('option:selected')
Or for multiple
use:
$(this).val();
Use like this:
<script>
$('#list').on("select2-selecting", function(e) {
var val = $(this).val();
alert(val);
});
</script>
Example:
$("#list").select2();
$('#list').on("change", function(e) {
var val = $(this).val();
alert(val);
});
#list {
width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<select id="list" multiple>
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Upvotes: 2
Reputation: 4287
You should persist in you js code currently selected list and in this onSelect
callback find difference, alert it and persist new selection
Upvotes: 0