user669677
user669677

Reputation:

index of selected item

I would like to get the selected item's index using jquery. I have tried some possibilities but I always got "undefined".

<select name="atvetel_mod" id="atvetel_mod">
<option value="0">kérem válasszon</option> 
<option value="1">Személyesen</option> 
<option value="2">Futár</option> 
<option value="3">Posta</option> 
</select>

$('#atvetel_mod').change(function() {
    alert($("#atvetel_mod").attr("selectedIndex"));
});

Thanks.

Upvotes: 0

Views: 3494

Answers (7)

iDusko
iDusko

Reputation: 53

$('#atvetel_mod option:selected').index()

Upvotes: 0

Robbiegod
Robbiegod

Reputation: 1014

Or if you want to get the actual value of the item you selected from the drop down menu you can also do this...I combined a couple of the answers found on this thread to come up with this answer.

 function showother(){
      var test = jQuery("#institution option:selected").val();
      if(test !== 'other') {

              jQuery("#other_field").css("display","none");

      } else {

        jQuery("#other_field").css("display", "block");

       }
   };

The reason I did this way instead of using the index is because I wanted an extra form field to appear only if the user chose "other" from my drop down menu. If they choose anything else, the extra field disappears. The menu is dynamically populated and i want to put the other option at the very bottom of the list. This is why the index won't work for me. I think this method is more flexible because then you can choose what values you want to check for instead of being locked into the index of the select menu.

So to use this function with a drop down menu just add an onchange="showother()" to your select menu. The function will run and grab the value from the selected item, perform the checks on the value and decide if needs to show the div with id="other_field" with the extra form field in it. And that's it.

Upvotes: 0

jerone
jerone

Reputation: 16871

Still answering the question of getting the index of a dropdown; in 1.6+ you can just do:

var index = $("#foo").prop("selectedIndex");

Upvotes: 5

Jatin Dhoot
Jatin Dhoot

Reputation: 4364

It should work.

You can try this

$("#selectID option").index($("#selectID option:selected"))

Upvotes: 3

fabian_p
fabian_p

Reputation: 107

$('#atvetel_mod').change(function() {       
          var index;          
          $('#atvetel_mod option:selected').each(function () {
                index = $(this).val();
          });          
          alert(index);      
});

Upvotes: -1

Jad
Jad

Reputation: 932

I think it's

$("#atvetel_mod").val()

Upvotes: 0

Gaurav
Gaurav

Reputation: 28755

you can use this

alert($(this).val());

Upvotes: 0

Related Questions