如何动态地插入表格行与选择框中的选项使用JavaScript表中的选项? [英] How to dynamically insert a table row with a select box with options in a table using javascript?
问题描述
我很难动态插入表行,因为我之前没有真正尝试过。我应该做的是插入一个新的表格行,其中包含一个选择框,其中包含arraylist的选项。
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
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
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);
}
也想知道如何将一个变量从javascript函数传递给一个java servlet,因为每次我以隐藏的输入类型传递变量计数时,输入不包含计数。我希望你能帮我解决我的困境。
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.
推荐答案
创建select元素之后您可以简单地遍历arraylist并追加选项:
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);
}
看看这个小提琴: https:/ /jsfiddle.net/bafforosso/66h3uwtd/2/
这篇关于如何动态地插入表格行与选择框中的选项使用JavaScript表中的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!