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.
Still answering the question of getting the index of a dropdown; in 1.6+ you can just do:
var index = $("#foo").prop("selectedIndex");
It should work.
You can try this
$("#selectID option").index($("#selectID option:selected"))
you can use this
alert($(this).val());
I think it's
$("#atvetel_mod").val()
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.
$('#atvetel_mod option:selected').index()
$('#atvetel_mod').change(function() {
var index;
$('#atvetel_mod option:selected').each(function () {
index = $(this).val();
});
alert(index);
});
精彩评论