i have a select fieldwith an optiongroup on a website that will be populated by ajax.
<select id="wlistid" name="wlistid">
<optgroup label="My List"></optgroup>
<optgroup label="Brother List">
<option value="5">First</option>
<option value="8">Second</option>
</optgroup>
</select>
i use this code to load the select:
$('#wlistid').load('ajax.php',{'ajaxcall':'getOptions');
this code runs on page load.
Now i like to get the selected element of this select field. I try
$('select[name=wlistid]').on('change', function() {
var listid=$('#wlistid').children('option:selected').val();
alert('ID '+listid);
});
But it is still undefined.
If i remove the optgroup and change my select to:
<select id="wlistid" name="wlistid">
<option value="5">First</option>
<option value="8">Second</option>
</select>
The code above works and alert the correct value.
But i like to use the optgroup. Who can help?
2
Answers
You are over complicating things.
Your use of children is incorrect in this case since the options are not children of the select but of the optgroup.
Just do
Your issue is caused by the use
$("select").children("option")
– this will only find "immediate-children".As your
option
is a child ofoptgroup
, your code doesn’t find (any)option
s.In the case where you need the
<option>
and not just theselect
‘s value, you can change to use.find
to get theoption
:Updated snippet: