简体   繁体   中英

How to dynamically insert a table row with a select box with options in a table using javascript?

I am having a hard time in inserting table rows dynamically since I haven't really tried it before. What I'm supposed to do is to insert a new table row with a select box with options from the an arraylist.

So far, this is my code:

HTML

<TABLE id="dataTable">         
    <TR>             

        <TD> 1</TD>             
        <TD> 
            <select name="option">
            <%for(int i = 0; i < jList.size(); i ++){%>
            <option value="<%=jList.get(i).getName%>"><%=jList.get(i).getName%></option>
            <%}%>
            </select>
        </TD>         
    </TR>     
    </TABLE> 
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />  

JAVASCRIPT

function addRow(tableID) {               
    var table = document.getElementById(tableID);               
    var rowCount = table.rows.length;         
    var count = rowCount + 1;
    var row = table.insertRow(rowCount);               
         //*** EDIT ***               
    var cell1 = row.insertCell(0);             
    cell1.innerHTML = count;
    var cell2 = row.insertCell(1);             
    var element2 = document.createElement("select");   
//how do i put the options from the arraylist here?
    cell2.appendChild(element2);  



}

also, I would also like to know how to pass a variable from the javascript function to a java servlet because every time I pass the variable count in a hidden input type, the input does not contain the count. I hope you can help me with my dilemma.

Just after you create the "select" element You can simply loop through your"arraylist" and append the options :

function addRow(tableID) {               
    var table = document.getElementById(tableID);               
    var rowCount = table.rows.length;         
    var count = rowCount + 1;
    var row = table.insertRow(rowCount);               
        //*** EDIT ***               
    var cell1 = row.insertCell(0);             
    cell1.innerHTML = count;
    var cell2 = row.insertCell(1);             
    var element2 = document.createElement("select");

    //Append the options from the arraylist to the "select" element
    for (var i = 0; i < arraylist.length; i++) {
        var option = document.createElement("option");
        option.value = arraylist[i];
        option.text = arraylist[i];
        element2.appendChild(option);
    }

    cell2.appendChild(element2);  
} 

Take a look at this fiddle : https://jsfiddle.net/bafforosso/66h3uwtd/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM