Search code examples
javascriptjqueryoptgroup

How to Dynamically Create <option> elements within a parent <optgroup>


I am trying to dynamically generate a structure similar to

 <select>
     <optgroup>
         <options> option 1 </option>
          <options> option 2 </option>
                   etc..
      </optgroup>
 </select>

using the following code. As you can see from the debug screen I can't seem to get the options embedded within the <optgroup>. Can anyone help please?

    milestoneData =[{"phase_ID":21,"phase_name":"hello1"}, {"phase_ID":22,"phase_name":"hello2"}]
    var optionGroup = document.createElement("optgroup");
    optionGroup.setAttribute("label","Project 1");
    optionGroup.setAttribute("value","100");
    $(".test").append(optionGroup).attr("id","theid");
    for (var i = 0; i <  milestoneData.length; i++) {
        var option = document.createElement("option");
        option.setAttribute("value",milestoneData[i].phase_ID);
        option.innerHTML=milestoneData[i].phase_name;
        $('#theid').append(option);
   }

HTML anchor is <select id = "testid" name = "testing" class ="test" >

render produced by above code


Solution

  • You are almost there, the problem you currently have its at $(".test").append(optionGroup).attr("id","theid");

    You currently are saying append optionGroup to .test and add id to .test element, which in your case you should add the id to optionGroup

    So it would be something like this:

    $(document).ready(function() {
       milestoneData =[{"phase_ID":21,"phase_name":"hello1"}, {"phase_ID":22,"phase_name":"hello2"}]
    
        var optionGroup = document.createElement("optgroup");
        optionGroup.setAttribute("label","Project 1");
        optionGroup.setAttribute("value","100");
        optionGroup.setAttribute("id","theid");
    
        $(".test").append(optionGroup);
    
       for (var i = 0; i <  milestoneData.length; i++) {
            var option = document.createElement("option");
            option.setAttribute("value",milestoneData[i].phase_ID);
            option.innerHTML=milestoneData[i].phase_name;
    
            $('#theid').append(option);
       }
    });
    

    I've created a quick jsfiddle for you: https://jsfiddle.net/gcpn10kd/1/

    You can check here some examples how optgroup should be structured