i have this situation:
i cannot get the selected value of a bootstrap-select with multiple=true
i can only get the first item?
so, when i first select Mustard, i get the alert for “Mustard”, but when i select after that Ketchup, i still get “Mustard”?
How can i get the value of the last selected or deselected item?
$(function() {
$('.selectpicker').on('change', function(){
var selected = $(this).find("option:selected").val();
alert(selected);
});
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
<select class="selectpicker" multiple="true">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>
<select class="selectpicker" multiple="true">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
2
Answers
You might need to loop through
options selected
when there are multiple. For ex as below:the issue in your code is
$(this).find("option:selected").val()
As @Guruprasad Rao said there is no need of looping just remove
.find("option:selected")
in above lineAnd if you want to get the last element selected then you have use array and store the element that is selected in it