[英]Auto Increment HTML table row value dynamically using jQuery
我有一個HTML表,如下所示。
<table id="items">
<tbody>
<tr>
<th>SlNo</th>
<th>Item</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr class="item-row">
<td class="item-name">
<div class="delete-wpr"><input type="text" value="1" class="slno"/> <a class="delete" href="javascript:;" title="Remove row">X</a></div></td>
<td><input type="text" class="slno"/></td>
<td><input type="text" class="cost"/></td>
<td><input type="text" class="qty"/></td>
<td><span class="price"></span></td>
</tr>
<input type="button" value="submit" onClick="storeAndShowTableValues()"/>
</tbody>
<tr id="hiderow">
<td colspan="5"><a id="addrow" title="Add a row">Add a row</a></td>
<!-- href="javascript:;" -->
</tr>
</table>
添加按鈕完美地工作了。 隨着每行的添加,Sl:no增加。 我也可以刪除行。 但是問題出在數字上。 想象有7行。 如果刪除第6行,則應重新調整行。 所以我在想,每當刪除一行時,都調用一些jQuery函數,該函數將按遞增順序重置第一行中的所有數字。 我在jQuery中使用以下功能,但不起作用。
以下添加行腳本可以正常工作。
$("#addrow").click(function(){
index1++;
window.globalCounter++;
$(".item-row:last").after('<tr class="item-row"><td class="item-name"><div class="delete-wpr"><input type="text" value="'+index1+'" class="slno"/><a class="delete" href="javascript:;" title="Remove row">X</a></div></td><td><input type="text" class="slno"/></td><td><input type="text" class="cost"/></td><td><input type="text" class="qty"/></td><td><span class="price"></span></td></tr>');
if ($(".delete").length > 0) $(".delete").show();
bind();
});
刪除行功能也可以,但是重新排序表索引的腳本不起作用。 所以我在考慮,一旦按下按鈕刪除一行,執行一個jQuery,它首先刪除選中的行,然后從1重置所有數字的索引。
$('#items').on('click', ".delete", function(){
$('#items').find('tr').find('td:first').each(function(index){ //This function doesnt work.
$(this).text(index+1);
});
$(this).parents('.item-row').remove();
if ($(".delete").length < 2) $(".delete").hide();
});
一種簡單的方法是忘記您現在使用的數字,並在輸入中設置名稱屬性。 如果將它們制成數組,它們將作為索引為0的列表自動發送:
<input name="slno[]" type="text" class="slno"/>
// etc.
現在,您可以輕松地序列化表單,發送表單並在后端對其進行處理,而無需手動構建數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.