如何将输入字段(文本框)添加到使用jQuery动态创建的表中
我一直在使用Javascript探索如何动态创建文本框和动态表.我想出了如何创建文本框和表格的方法,但是我不知道如何将这些文本合并在一起,以便动态创建的表保存具有我首选参数的文本框.
I have been playing with Javascript to find out how i can dynamically create textboxes and a dynamic table. I figured out how to create the textboxes and the table, but i dont know how to merge theese together, so that the dynamically created table holds the textboxes with my preferred parameters.
我有这个jQuery脚本,它可以动态地向表中添加行和单元格.我在名为"element"的输入字段中指定表格应包含的行数
I have this jQuery script which dynamically adds rows and cells to a table. I specify how many rows the table should have in an input field called "element"
HTML:
<input type="text" name="element" id="element" />
<input type="button" value="Tilføj" id="add" />
<br />
<span id="MCQ-textbox">
<table id="tbl" border="1">
<tbody>
</tbody>
</table>
</span>
脚本:
<scripts language="javascript">
function createDynamicTable()
{
var tbody = $("#tbl");
var rows = $('#element').val();
var number_of_columns = 3;
if (tbody == null || tbody.length < 1) return;
var tfirstrow = $("<tr>");
$("<th>")
.addClass("tableCell")
.text("#")
// .data("col")
.appendTo(tfirstrow);
$("<th>")
.addClass("tableCell")
.text("Svarmulighed")
// .data("col")
.appendTo(tfirstrow);
$("<th>")
.addClass("tableCell")
.text("Hjælpetekst")
// .data("col")
.appendTo(tfirstrow);
tfirstrow.appendTo(tbody);
for (var i = 0; i < rows; i++) {
var trow = $("<tr>");
for (var c = 0; c < number_of_columns; c++)
{
var cellText = "Cell"
$("<td>")
.addClass("tableCell")
.text(cellText)
.data("col", c)
.appendTo(trow);
}
trow.appendTo(tbody);
}
}
$(document).ready(function () {
$('#add').click(function () {
createDynamicTable();
});
});
</SCRIPT>
我想添加文本框,而不是在每列中添加文本单元格".
Instead of adding the text "cell" to each column, i would like to add textboxes.
第一列应具有以下属性:
The first column should have the following attributes:
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("id", "MCQ_"+i+"__choice_number");
element.setAttribute("name", "MCQ["+i+"].choice_number");
第二列应具有以下属性:
the second column should have the following attributes:
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("id", "MCQ_"+i+"__choice_wording");
element.setAttribute("name", "MCQ["+i+"].choice_wording");
,第三列应具有以下属性:
and the third column should have the following attributes:
var element = document.createElement("input");
element.setAttribute("type", "text");
element.setAttribute("id", "MCQ_"+i+"__help_text");
element.setAttribute("name", "MCQ["+i+"].help_text");
我该如何合并它,以便我的表包含上面带有参数的文本框?
How do i merge this, so that my table holds the textboxes with the parameters above?
谢谢!
这将起作用: http://jsfiddle.net/RrhT9/
此外,您可以按照自己的方式将内容添加到单元格中,但必须替换.text("<input.../>")
与.html("<input.../>)
Also, you could have added content to the cell your way, but you'd have to replace .text("<input.../>")
with .html("<input.../>)