Add new row to the table containing a drop down li

2019-08-28 17:42发布

问题:

I want to add a new row on button click to a table. New Row will have one textbox and one drop-down. Dropdown (select element)'s options to be added from session attribute.

I am able to add textbox using following function.

    function addRow(btn) {         
        var parentRow = btn.parentNode.parentNode;
        var table = parentRow.parentNode;
        var rowCount = table.rows.length;

        var row = table.insertRow(rowCount);

        var cell1 = row.insertCell(0);
        var element1 = document.createElement("input");
        element1.type = "text";
        element1.name="abc";
        cell1.appendChild(element1);
        var cell3 = row.insertCell(1);
        var element2 = document.createElement("select");
        var option1 = document.createElement("option");
        option1.innerHTML = "Option1";
        option1.value = "1";
        element2.appendChild(option1, null);
    }

I have one session attribute "types". I want to add one drop down list as other column to the row where options are to be added from types. I am setting the attribute "types" when page gets loaded. I am using Java Servlet for server side. Any help is appreciated.

<c:forEach items="${types}" var="type">

回答1:

If u have session attribute "types" then u can do like this. Post ur remaining coding so i can update my answer.

var Type = 'option 1';

function AddRow() {
    $('#tblTest').append(
        '<tr><td>' +
          '<input type="text" />' +
          '<select><option>' + Type + '</option></select>' +
        '</td></tr>');
}

<table id="tblTest">
    <tr>
        <td>
            <input type="text" name="data1" value="TempData" />
        </td>
        <td>
            <input type="button" value="Add" onclick="AddRow()" />
        </td>
    </tr>
</table>