如何解决如何使用javascript或jquery创建按钮的动态tbody onclick
我有此代码:
$(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" />
我该如何实现?
解决方法
这就是您要寻找的东西:
$(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))
条件下插入多少行的控件(如果需要更多或更少的行,则唯一需要编辑的就是数字)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。