如何在JQuery中对表行进行连续编号



我有这个HTLM和JQuery:

JQuery

$(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></td>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: 10n" +
"- Inserted: " + rows);
}
});
});

我已经能够在tbody 中生成td

HTML

<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">SN</th>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>
</body>

row_no的值决定了要形成的td行的数量。

如何为行生成序列号(SN(?

感谢

一种方法:

$(document).ready(function() {
var tbody = $('#myTable').children('tbody');
var table = tbody.length ? tbody : $('#myTable');
$('[name=row_no]').text();
$('button').click(function() {
var rows = $('[name=row_no]').val();
var num_rows = $("#myTable tbody tr").length;
if (rows < 11) {
var sn;
for (var i = 0; i < rows; i++) {
sn = num_rows + i;
table.append(`<tr>
<td>${sn}</td>
<td><input name="product_name[]" type="text"/></td>
<td><input name="qty[]" type="text"/></td>
<td><input name="price[]" type="text"/></td>
</tr>`);
}
}
else {
alert("Error: Too many rows!n" +
"Maximum allowed: 10n" +
"- Inserted: " + rows);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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">SN</th>
<th class="column-title">Product name</th>
<th class="column-title">Quantity</th>
<th class="column-title">Price</th>
</tr>
</tbody>
</table>

最新更新