Get the value of the" option " that was clicked either to select/deselect
I have the following <select>
:
<select id="multiselect" multiple="multiple">
<option value="pedra">Pedra</option>
<option value="papel">Papel</option>
<option value="tesoura">Tesoura</option>
</select>
With the jQuery code below, I can get the value of the last selected <option>
:
<script type="text/javascript">
$(document).ready(function() {
$('#multiselect').multiselect();
$(document).on('change','#multiselect', function(){
console.log (( $('option', this).filter(':selected:last').val() ))
});
});
</script>
However, what I really wanted was to get the value of the clicked <option>
(I know that on('click', func..)
will not work in this case), regardless of whether it is being selected or deselected.
I researched a lot,but the most I found, was how to find the value of the last selected.
The plugin used is the Bootstrap-multiselect
3 answers
Try to use like this:
$('#multiselect').multiselect();
$("#multiselect").on("multiselectclick", function (event, ui) {
console.log(ui.value);
});
Example
Found this in the documentation:
$("#multiselect").on("multiselectclick", function(event, ui) { /* event: the original event object ui.value: value of the checkbox ui.text: text of the checkbox ui.checked: whether or not the input was checked or unchecked (boolean) */ });
To achieve the effect you expect, you need to put a handler for each element option :
$("#multiselect").on("click", "option", function() {
var clickedOption = $(this);
alert(clickedOption.val());
});
Working code example:
Example with console.log (without alert):
$("#multiselect").on("click", "option", function() {
var clickedOption = $(this);
console.log(clickedOption.val());
});
Solved
Guys, thank you for your attention. The plugin I'm using is the Bootstrap-Multiselect. I don't know if there is a more elegant and better solution, but, I managed to solve like this:
$(document).ready(function() {
$('#multiselect').multiselect({
onChange: function(element, checked) {
console.log(element[0]['value']);
}
});
});