Ashish Patil
Ashish Patil

Reputation: 55

in multiselect how can i get the clicked value using jquery

Multi Select Option i Get The Clicked Value Only Using jquery.

$(document).ready(function() {
  $("#mySelect").change(function() {

    var firstselected = $(':selected', this).val(); //returns first selected in list
    var lastselected = $(':selected:last', this).val(); //return last selected in list
    alert(firstselected);
    alert(lastselected);
    // what if i want exact option i have clicked in list 
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect" class="selectpicker" multiple>
  <option>Option1</option>
  <option>Option2</option>
  <option>Option3</option>
  <option>Option4</option>
  <option>Option5</option>
  <option>Option6</option>
  <option>Option7</option>
</select>

var firstselected = $(':selected', this).val();//this returns first selected in list
var lastselected = $(':selected:last', this).val();//this return last selected in list 

what if i want exact option i have clicked in list whether it is in middle of selected options list

Upvotes: 2

Views: 3823

Answers (4)

remonses
remonses

Reputation: 412

You can get the clicked value using the following solution:

$("#mySelect").on('change', function(e) {
  e.currentTarget.value  //should return you the currently selected option
});

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

you can get both all selected and current selected value

$("#mySelect option").click(function (e) {

    var all = $("#mySelect :selected").map(function () {
        return this.value;

    }).get();  // all selected value

    if (all.indexOf(this.value) != -1) {  // check the condition your selecting or unselected  option
        alert(this.value);  // current selected element
    }

});

NOTE: you can get all selected value using all variable, and you can get current selected value also

DEMO

Upvotes: 3

Saif
Saif

Reputation: 7052

This will give you all the option you have selected from the first to last.

$(':selected',this).each(function(i, selected){ 
  alert($(selected).val());
});

But if you want to get only the option that is just can add click listener to the options.

$("#mySelect").on('click','option',function(){
    alert($(this).val());
});

Upvotes: 0

K K
K K

Reputation: 18099

You will need to bind events on option also:

$("#mySelect").on("click", "option", function () {
    console.log($(this)); //this will log the clicked option.
});

Demo :http://jsfiddle.net/lotusgodkk/GCu2D/725/

Upvotes: 0

Related Questions