【问题标题】:How to Create dynamic tbody onclick of button using javascript or jquery如何使用 javascript 或 jquery 创建按钮的动态 tbody onclick
【发布时间】:2020-12-25 21:33:29
【问题描述】:
我有这个代码:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('button').click(function() {
//Add row
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="row_no" type="text" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
当我点击按钮添加行时,它会在表格中添加一行。
但是现在,我在 HTML 中有一个文本框。我想附加表以根据以下值生成行:
<input name="row_no" type="text" placeholder="Type Your Number of row" />
我如何做到这一点?
【问题讨论】:
标签:
javascript
html
jquery
dynamic
【解决方案1】:
这就是您要查找的内容:
$(document).ready(function() {
//Try to get tbody first with jquery children. works faster!
var tbody = $('#myTable').children('tbody');
//Then if no tbody just select your table
var table = tbody.length ? tbody : $('#myTable');
$('[name=row_no]').text();
$('button').click(function() {
var rows = $('[name=row_no]').val();
// If rows are at maximum 10,
if (!(rows > 10)) {
// then add rows
for (var i = 0; i < rows; i++) {
table.append('<tr>\n\
<td><input name="product_name[]" type="text"/></td>\n\
<td><input name="qty[]" type="text"/></td>\n\
<td><input name="price[]" type="text"/></td>\n\
</tr>');
}
}
else {
alert("Error: Too many rows!\n" +
"Maximum allowed: 10\n" +
"- Inserted: " + rows);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input name="row_no" type="number" placeholder="Type Your Number of row" />
<button>Add row</button>
<table id="myTable">
<tbody>
<tr>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
</body>
发生了什么变化?
- 您需要在文本字段中插入值,这可以使用,在这种情况下:
$('[name=row_no]').val();,所以我将其定为rows 变量,然后唯一要添加的是一个循环创建为用户插入的行数。
- 我也将
<input name="row_no" type="text" placeholder="Type Your Number of row" />
更改为<input name="row_no" type="number" placeholder="Type Your Number of row" />。
这个小改动允许用户只插入整数,这是一个很好的解决方案,可以避免由于编写新函数而造成的时间损失验证插入的值。
编辑:
- 添加了一个关于用户可以使用
if (!(rows > 10)) 条件插入多少行的控件(如果您需要更多或更少的行,唯一需要编辑的是数字)