3 回答

TA貢獻1862條經驗 獲得超6個贊
您不需要 id 來從輸入元素獲取值,我們可以輕松地動態獲取每個輸入的值,請檢查下面的代碼。
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($(item).find('input[type=number]').val());
});
});
https://jsfiddle.net/n7dzhwk4/

TA貢獻1827條經驗 獲得超8個贊
我認為更明智的選擇是交換值,而不是更改 ID。您可以通過將onclick刪除操作更改為:
$('tbody').on('click', '.remove', function(){
elements = $(".cb");
current = parseInt($(this).id);
for (let itr = current; itr < elements.length - 1; itr++) {
elements[itr].value = elements[itr + 1].value;
}
elements[elements.length - 1].remove();
i--;
});
這是代碼: https: //jsfiddle.net/ckpLqs4g/

TA貢獻1784條經驗 獲得超7個贊
試試這個,實際上這不是解決這個問題的最佳方法,你真的不需要動態更改id,但我希望這會對你有所幫助
$('.addRow').on('click', function(){
addRow();
});
function addRow()
{
var rowCount = $('.listable tr').length -1;
var tr = '<tr class="cb" id="row_'+rowCount+'"><td>';
tr += '<select class="form-control select2" id="name1_'+rowCount+' first" name="name[]">';
tr += '<option id="1">tan</option><option id="2">lim</option></select></td>';
tr += '<td><input type="number" name="winlose[]" id="amt1_'+rowCount+'" class="form-control"></td>';
tr += '<td style="text-align:center"><a href="#" class="btn btn-danger remove">-</a>';
tr += '</td></tr>';
i++;
let elementCount = 0
$('tbody').append(tr);
$('tbody').children('tr').each(function () {
this.attr('id',`row_${elementCount}`);
elementCount++;
});
}
$('tbody').on('click', '.remove', function(){
$(this).parent().parent().remove();
});
$('.savebtn').on('click', function(){
$('.listable .cb').each(function(index, item){
console.log($('#amt1_'+index).val());
});
});
- 3 回答
- 0 關注
- 147 瀏覽
添加回答
舉報