3

我使用 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);
        });
    });
});
4

1 回答 1

3

您可以使用 jQuery UI 中的uniqueId()方法。它将应用于一组匹配的元素,因此您只需将其应用于您#dynamic-tbl的输入字段:

$('#dynamic-tbl input').uniqueId()

如果您不想使用 jquery,您也可以编写自己的函数来创建唯一 id:

function uniqId() {
  return Math.round(new Date().getTime() + (Math.random() * 100));
}

如果您只希望 id 的数字在增加,并且您还可以修改 addTableRow 函数以在将 html 复制到下一行之前更改 id:

$(this).find('input').attr("id","itemId" + rowId);
于 2016-01-30T10:15:40.287 回答