[英]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.