javascriptoptgroup

Javascript grouping of option of select by optgroup


i am trying to group my option values in optgroups. I currently have the options saved as
--model--
AUDI#A4 (2003-2009)
AUDI#A5 (2003-2009)
VW#Passat B7 (2003-2009)
VW#Passat B8 (2003-2010)

With JS they should be grouped like:
--model--
AUDI
A4 (2003-2009)
A5 (2003-2009)
VW
Passat B7 (2003-2009)
Passat B8 (2003-2010)

I have the following code which builds the options


      for (var i=0;i<l;i++){
      var opt = options[i].split('#');
        select[0].options[i+1] = new Option(opt[1],options[i]);

    }

I can manage to split the text of option by the charachter # and add the first option after the default option/text "--model--". Can someone please help with grouping with optgroup.

Thanks in advance


Solution

  • If you are getting data form your database in the form of an array you can do something like this

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>make select element</title>
    </head>
    <body>
        <script>
            let arr = [
                "AUDI#A4 (2003-2009)",
                "AUDI#A5 (2003-2009)",
                "VW#Passat B7 (2003-2009)",
                "VW#Passat B8 (2003-2010)"
            ]
            let tempObj = {}
            arr.forEach(val =>{
                let newVal = val.split("#");
                if (tempObj[newVal[0]] === undefined) {
                    tempObj[newVal[0]] = [newVal[1]]
                }else{
                    tempObj[newVal[0]].push(newVal[1])
                }
            })
            let selectElement = document.createElement("select");
    
            for (const val in tempObj) {
                let createOpt = document.createElement("optgroup");
                createOpt.setAttribute("label",val)
    
                tempObj[val].forEach(value =>{
                    let option = document.createElement("option");
                    option.innerText = value;
                    createOpt.appendChild(option);
                })
                selectElement.appendChild(createOpt);
            }
    
            document.body.appendChild(selectElement);
    
                
        </script>
    </body>
    </html>