skip to Main Content

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


  1. 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

    $('#wlistid').on('change', function() {
      var listid = this.value
      console.log('ID', listid);
      // alternatives
      console.log('ID', $(this).val());
      console.log('ID', $("option:selected",this).val())
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <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>
    Login or Signup to reply.
  2. Your issue is caused by the use $("select").children("option") – this will only find "immediate-children".

    As your option is a child of optgroup, your code doesn’t find (any) options.

    In the case where you need the <option> and not just the select‘s value, you can change to use .find to get the option:

    $('#wlistid').find('option:selected');
    

    Updated snippet:

    $('select[name=wlistid]').on('change', function() {
      var opt = $('#wlistid').find('option:selected');
      console.log(opt.val(), opt.data("details"));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="wlistid" name="wlistid">
      <optgroup label="My List"></optgroup>
      <optgroup label="Brother List">
        <option value="5" data-details='this one'>First</option>
        <option value="8" data-details='the other one'>Second</option>
      </optgroup>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search