如何在laravel中正确实现CRUD json字段



使用以下代码,我为不同数量的产品属性动态添加字段:

$("#addRow").click(function () {
var html = '';
html += '<div id="inputFormRow">';
html += '<div class="input-group mb-3">';
html += '<input type="text" name="properties[{{i}}][key]" class="form-control m-input ml-3" value="{{ old('properties['.$i.'][key]') }}" placeholder="Key" autocomplete="off">';
html += '<input type="text" name="properties[{{i}}][value]" class="form-control m-input ml-3" value="{{ old('properties['.$i.'][value]') }}" placeholder="Value" autocomplete="off">';
html += '<div class="input-group-append ml-3">';
html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
html += '</div>';
html += '</div>';

$('#newRow').append(html);
});
// remove row
$('#removeRow').on('click', function () {
$(this).closest('#inputFormRow').remove();
});

这是我的html

@isset($product)
@foreach($product->properties as $i=>$prod)
<div class="input-group mb-3">
<input type="text" name="properties[{{ $i }}][key]" value="{{ $prod[$i]['key'] }}" class="form-control m-input ml-3" placeholder="Key" autocomplete="off">
<input type="text" name="properties[{{ $i }}][value]" value="{{ $prod[$i]['value'] }}" class="form-control m-input ml-3" placeholder="Value" autocomplete="off">
<div class="input-group-append ml-3">
<button id="removeRow" type="button" class="btn btn-danger">Remove</button>
</div>
</div>
@endforeach
@endisset
<div id="newRow"></div>
<button id="addRow" type="button" class="btn btn-info">Add field</button>

但我不能制作动态计数器,以后如何编辑这些字段?如何添加/删除?我从这个实现中得到了这个想法,但为了简单起见,他们使用了固定数量的字段,这很容易,但如何使用动态字段呢?

第一个(用于动态计数器(将此i变量添加到addRow选择器之前。然后在.click()功能内增加

let i = 0;
$("#addRow").click(function () {
i++;
// now do your append() code
}

第二行(添加/删除行(用于添加行的Html+jquery代码已经存在。(Your Remove code may not work for multiple non-unique id)要删除一行,请在<div id="inputFormRow">下面添加一个button,该行带有一个类,比如dynamic-remove,如下所示:

<div id="inputFormRow">
<button type="button" class="dynamic-remove">Remove</button>

然后为onclick添加jquery代码:

$('.dynamic-remove').click(function(){
$(this).parent().remove()
})

第三行(编辑动态行(使用foreach,放置要附加的html代码并填充它们:

@foreach($model_array as $i => $model)
// your html code populated via $model object
@endforeach