Sadikhasan
Sadikhasan

Reputation: 18598

Get index or value of clicked option from multiple select

I have multiple select in which I want to clicked option on which I cliked.

E.g. If I click on first option then display first option index or value.

HTML Code

<select class="founder_designation" rel="Designation" placeholder="Designation" multiple="multiple" name="designation">
<option value="">-- Select Designation --</option>
<option value="chairman_managing_director">Chairman &amp; Managing Director</option>
<option selected="selected" value="director" >Director</option>
<option value="whole_time_director">Whole Time Director</option>
<option value="other">Other</option>
</select>

jQuery Code

$(".founder_designation").on("change",function(){
  alert($(this).val());   //It display all selected options with comma separated
})

JS Fiddle

Upvotes: 0

Views: 3978

Answers (4)

ahmmaad gamal
ahmmaad gamal

Reputation: 1

let previouslySelected = []; // declare as a global array

$("#your-select-picker-id").change(function () {

    let currentlySelected   = $(this).val(); // ids [1, 2, 3]
    let isAdding            = currentlySelected.length > previouslySelected.length;

    if ( isAdding )
    {
        lastSelectedId = currentlySelected.find( ( element ) => ! previouslySelected.includes(element) )
    }
    else
    {
        lastSelectedId = previouslySelected.find( ( element ) => ! currentlySelected.includes(element) )
    }
    previouslySelected = currentlySelected;
});

Upvotes: 0

Janne L
Janne L

Reputation: 11

$(".founder_designation").on("change",function(e){
  alert(e.target.value);
  // OR
  alert($(e.target).val());
});

Upvotes: 1

Domain
Domain

Reputation: 11808

this will do the trick,

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

if you want all the value then try some thing like this,

$('.founder_designation').on('click','option',function(){

    alert("clicked value:"+$(this).val());

    $a=$('.founder_designation option:selected');
    $str='';
    for($i=0;$i<$a.length;$i++){
        $str+=$('.founder_designation option:selected:eq('+$i+')').val()+",";
    }

    alert("all selected :"+$str);
});

Check the demo JS FIDDLE DEMO

Upvotes: 2

JasonK
JasonK

Reputation: 5294

This should do the trick:

$('.founder_designation option:selected').val();

If you have several selects with the classname founder_designation you could do this:

$('.founder_designation option').click(function(e) {
   var value = $(this).val();
   alert(value);
});

Upvotes: 1

Related Questions