[英]jQuery how to add unique id to dynamic form input fields
我使用Laravel刀片模板創建了這個表單,並使用jQuery使其動態化。 現在我可以使用其中的所有輸入字段填充表行。 現在我正在嘗試將ajax數據輸入到第一列中更改選擇值的那些字段中。 它僅適用於第一行,因為每個輸入字段沒有唯一的ID。 請幫我解決這個問題。
以下代碼用於刀片模板上的表單
<tr id="1">
<td>
{!! Form::select('item_id[]', ['' => 'Select an item'] + $items, null, array('class' => 'form-control', 'id' => 'itemId', 'required')) !!}
</td>
<td>
{!! Form::text('item_description[]', null, ['class' => 'form-control', 'id' => 'item_description', 'placeholder' => 'Not Required | Optional']) !!}
</td>
<td>
{!! Form::text('units[]', null, ['class' => 'form-control', 'placeholder' => 'Add Units', 'required']) !!}
</td>
<td>
{!! Form::text('rate[]', null, ['class' => 'form-control', 'id' => 'rate', 'placeholder' => 'Add Rate', 'required']) !!}
</td>
<td>
{!! Form::text('amount[]', null, ['class' => 'form-control', 'placeholder' => 'Add Hrs and Rate', 'id' => 'amount']) !!}
</td>
<td class="text-center actions"><a id="delete-row" onclick="delTableRow($('#dynamic-tbl'));" href="#"><i class="fa fa-times"></i></a></td>
</tr>
以下代碼用於填充具有相同輸入字段的更多行
/*
* Dynamic table row adding and deleting functions
*/
function addTableRow(jQtable){
var rowId = parseInt($('#dynamic-tbl tbody tr:last').attr('id'));
++rowId;
// console.log(rowId);
jQtable.each(function(){
var tds = '<tr id='+rowId+'>';
jQuery.each($('tr:last td', this), function() {tds += '<td>'+$(this).html()+'</td>';});
tds += '</tr>';
if($('tbody', this).length > 0){$('tbody', this).append(tds);
}else {$(this).append(tds);}
});
}
在這里$(this).html()
復制上一行的內部html。 我正在嘗試為每個輸入字段添加唯一ID。
以及用於使用ajax獲取數據的代碼
/*
* Estimate Item Description Ajax function
*/
$('#dynamic-tbl #itemId').change(function(e) {
//console.log(e);
var item_id = e.target.value;
//ajax
$.get('/ajax-item?item_id=' + item_id, function(data){
//success data
//console.log(data);
$('#item_description').empty();
$('#rate').empty();
$.each(data, function(index, itemObj){
$('#item_description').val(itemObj.name);
$('#rate').val(itemObj.sale_price);
});
});
});
您可以使用jQuery UI中的uniqueId()方法。 它將應用於一組匹配的元素,因此您只需將其應用於#dynamic-tbl
的輸入字段:
$('#dynamic-tbl input').uniqueId()
如果您不想使用jquery,您還可以編寫自己的函數來創建唯一的id:
function uniqId() {
return Math.round(new Date().getTime() + (Math.random() * 100));
}
如果你希望id只有一個增加的數字,你也可以修改你的addTableRow函數來改變id,然后再將html復制到下一行:
$(this).find('input').attr("id","itemId" + rowId);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.