[英]How to dynamically add table rows in HTML table from value of input textbox
[英]Add rows to a html table from a textbox value
我想在文本框中多次输入第一行到同一张表中。
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr id="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" onclick="showRow()"/>
<input id="Text1" type="text" />
<script>
function showRow() {
var header = Array();
$("#row").each(function (i) {
header[i] = $(this).text();
})
alert(header);
}
</script>
因此,我创建了第一行的数组,当您单击按钮时会发出警报。 我的问题的一个例子:
如果我在文本框中输入5并单击按钮,则表格应如下所示:
ABC
123
123
123
123
123
这可能吗?
我制作了类row
而不是id
,以便我们可以将其作为目标( clone()
可以防止重复的id
。)
您可以将行存储为jQuery对象,然后使用for()
循环克隆该对象并将其附加。 使用在循环内的文本框中输入的值:
var $tbl = $('#table1'), origRow = $tbl.find('.row').first();
$('#Button1').on('click', function(){
var num = $('#Text1').val();
$tbl.find('.row').remove();
for(i=0; i<num; i++){
var newRow = origRow.clone();
$tbl.append(newRow);
}
});
我不确定您是希望表每次都为空还是仅将行添加到末尾。 如果要将行添加到末尾,只需删除$tbl.find('.row').remove();
线。
是Ofc,只需将文本框val()或value解析为int,然后将for()循环解析为该数字
使用jquery有很多方法可以做到这一点。 看一下这些jQuery函数:
clone()
appendTo()
insertAfter()
现场演示
尝试以下操作:将您的行更改为类。
HTML:
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr class="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" />
<input id="Text1" type="text" />
JQUERY:
$('#Button1').on('click',function(e) {
limit = $("#Text1").val();
for(i=0;i<parseInt(limit);i++) {
strText = $(".row").first().clone();
strText.appendTo("#table1");
}
});
您可以尝试以下一种方法:
逻辑很简单:从文本框中获取计数,无次数创建行计数,并将该行追加到表的最后一行之后。 $('#row').html()
将给出第一行的内部元素。
<script>
function showRow() {
var i, num = $('#Text1').val();
for(i=0; i<num; i++){
$('#table1 > tbody:last').append('<tr id=row'+i+1+'>'+$('#row').html()+'</tr>');
}
}
</script>
试试这个链接
<table id='table1'>
<tr>
<td>A</td><td>B</td><td>C</td>
</tr>
<tr class="row">
<td>1</td><td>2</td><td>3</td>
</tr>
<table>
<input id="Button1" type="button" value="button" onclick="showRow()"/>
<input id="Text1" type="number" />
$(document).ready(function () {
$('#Button1').click(function(){
var num = $('input[id="Text1"]').val();
alert(num);
for(var i=0;i<num;i++){
$('table[id="table1"]').append(' <tr class="row"><td>1</td><td>2</td><td>3</td></tr>');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.