如何根据输入的行数生成html表? [英] how to generate html table based on number of rows entered?
问题描述
我必须使用jquery创建一个表.该表的行数将在输入框中确定.列数是已知的.提交后,将生成一个表.试图制造一个小提琴. 对jquery非常新.不确定如何继续.
I have to create a table using jquery. The number of rows the table will be determined from input box. The number of columns are known. After submitting that, a table gets generated. Tried creating a fiddle. Am very new to jquery . Not sure how to proceed.
<form>
Number of rows to be generated
<br>
<input type="number" id="table-row-num" value="3">
<button>Submit</button>
</form>
<div id="table-gen">
<p>Table generated here after clicking submit</p>
<table cellpadding="1" cellspacing="1" border="1">
<tr>
<td>1</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>2</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
<tr>
<td>3</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
<td>
<input type="name" placeholder="text goes here...">
</td>
</tr>
</table>
</div>
推荐答案
这是您更新的小提琴: http://jsfiddle.net/fpd8dwtw/17/
This is your fiddle updated: http://jsfiddle.net/fpd8dwtw/17/
这是jquery代码:
This is the jquery code:
$("#submitButton").click(function() {
var table = $("#resultTable");
var rowNum = parseInt($("#table-row-num").val(), 10);
var resultHtml = '';
for(var i = 0 ; i < rowNum ; i++) {
resultHtml += ["<tr>",
"<td>",
(i+1),
"</td>",
'<td><input type="name" placeholder="text goes here..."></td>',
'<td><input type="name" placeholder="text goes here..."></td>',
'</tr>'].join("\n");
}
table.html(resultHtml);
return false;
});
祝您实施顺利. :)
I wish you luck with implementation. :)
如果要允许行数在最小和最大数之间的范围内,最好的解决方案是使用本机html 5验证. 这是jsfiddle:
If you want to allow number of rows to be on range between minimum and maximum number the best solution is to use native html 5 validation. This is jsfiddle:
http://jsfiddle.net/fpd8dwtw/20/
这篇关于如何根据输入的行数生成html表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!