Search code examples
javascripthtmlhtml-selectappendchild

Assign options to select input through javascript


I have a Select menu in my site, inside a table.

<select name = "menu" id="menu" >
   <option>A</option>
   <option>B</option>
   <option>C</option>
</select> 

I'm trying to do a JavaScript function to add another select menu with the same options in a row below of the table.
I have this:

function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var element1 = document.createElement("select");
    element1.id = "id";
    cell1.appendChild(element1);
}

But I don't know where to add the options in here.

I hope someone could help me.


Solution

  • If you want to copy it exactly anyway you could also use cloneNode() similar to this:

    function addRow(tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
    
        var cell1 = row.insertCell(0);
    
        // Get a handle to the original select
        var orgSelect = document.getElementById("menu");
    
        // Make a clone, using true to indicate we also want to clone child nodes
        var dupSelect = orgSelect.cloneNode(true);
    
        // Change any attributes of the new select
        dupSelect.id = "id";
    
        // Append the new select
        cell1.appendChild(dupSelect);
    }
    

    DEMO - Using cloneNode() to duplicate a select and options


    You could then even make this a function you call, passing any relevant parameters, similar to this:

    function createClone(elementId, newId, includeChildNodes){
        var original = document.getElementById(elementId);
        var duplicate = original.cloneNode(includeChildNodes);
    
        duplicate.id = newId;
    
        return duplicate;
    }
    
    // Call it like this
    var clonedElement = createClone('menu', 'newMenu', true);