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

 5
Author: Eric Vieira, 2014-02-11

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)
  */
});
 6
Author: Sergio, 2014-02-11 17:20:09

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:

Http://jsfiddle.net/ryNFE/2 /

Example with console.log (without alert):

$("#multiselect").on("click", "option", function() {
    var clickedOption = $(this);
    console.log(clickedOption.val());
});
 0
Author: Onilton Maciel, 2014-02-11 17:57:14

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']);
    }
  });
});
 0
Author: Eric Vieira, 2014-02-11 17:58:12