$('.excludeDaysPicker').selectpicker();
I have bootstrap selectpicker with 'multiple' choose option enabled.
<select class="excludeDaysPicker" multiple title="Not Selected">
<option value="Monday" id="1" class="excludeDays">Monday</option>
<option value="Tuesday" id="2" class="excludeDays">Tuesday</option>
<option value="Wednesday" id="3" class="excludeDays">Wednesday</option>
<option value="Thursday" id="4" class="excludeDays">Thursday</option>
<option value="Friday" id="5" class="excludeDays">Friday</option>
<option value="Saturday" id="6" class="excludeDays">Saturday</option>
<option value="Sunday" id="7" class="excludeDays">Sunday</option>
</select>
upon clicking the select option (either selecting or deselecting), I want to know which option is clicked.
I have tried.
$('.excludeDaysPicker').on('change',function(){
console.log("id::",$(this).children(':selected').attr('id'));
});
This actually does get me id. But since it is a multiple select enabled selectpicker. if already an option is selected. that option's id is get returned. for ex, in the screen shot below
if i click on wednesday, It gives me the id 2 (because tuesday is selected), But actually the id of wednesday is 3. I want the id of the option element i am clicking on.
And also I could not get the option element by giving the option element a class , because the the bootstrap selectpicker plugin creates a list for all the option element like you can see below.
so,
$('.excludeDays').click(function()
{
console.log("excluded day optionselected::",$(this).attr('id'));
});
doesn't help either.
is there way around guys?
To get the respective id's of the options selected :
$('.excludeDaysPicker').on('change',function(){
$(this).find("option:selected").each(function()
{
alert($(this).attr("id"));
});
});
UPDATE : To get the last selected value, push all selected values in the array and get the last element's id.
var arr = new Array();
$('.selectpicker').on('change', function(){
$(this).find("option").each(function()
{
if($(this).is(":selected"))
{
id = $(this).attr("id");
if(arr.indexOf(id) == -1)
{
arr.push(id);
}
}
else
{
id = $(this).attr("id");
arr = jQuery.grep(arr, function(value) {
return value != id;
});
}
});
if(arr.length > 0)
alert("Last selected id : " + arr[arr.length-1]);
});
来源:https://stackoverflow.com/questions/33571562/how-to-get-the-clicked-option-in-bootstrap-selectpicker