I'm trying to use jQuery to make an ajax request based on a selected option.
Is there a simple way to retrieve the selected option id (e.g. "id2") using jQuery?
<select id="my_select"> <option value="o1" id="id1">Option1</option> <option value="o2" id="id2">Option2</option> </select> $("#my_select").change(function() { //do something with the id of the selected option });
Getting the selected ID using the selectedIndex and options properties # The options property returns an HTMLOptionsCollection , an array-like collection of options for a select element. You can pair it with the selectedIndex property to get the selected option . Then, you can use the id property to get its ID.
$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").
$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });
You can get it using the :selected
selector, like this:
$("#my_select").change(function() { var id = $(this).children(":selected").attr("id"); });
var id = $(this).find('option:selected').attr('id');
then you do whatever you want with selectedIndex
I've reedited my answer ... since selectedIndex isn't a good variable to give example...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With