我正在尝试向 CakePHP View 中的 html 表中添加行,并在必要时增加 ID/名称。用于生成表格的代码是:
<tbody>
<tr>
<td><?php echo $this->Form->input('OrderDetail.0.product_code'); ?></td>
<td><?php echo $this->Form->input('OrderDetail.0.product_name'); ?></td>
<td><?php echo $this->Form->input('OrderDetail.0.product_qty'); ?></td>
<td><?php echo $this->Form->input('OrderDetail.0.product_price'); ?></td>
</tr>
</tbody>
CakePHP 输出以下 html:
<tbody>
<tr>
<td><div class="input text"><input name="data[OrderDetail][0][product_code]" maxlength="100" type="text"/></div></td>
<td><div class="input text"><input name="data[OrderDetail][0][product_name]" maxlength="255" type="text"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][0][product_qty]" step="any" type="number"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][0][product_price]" step="any" maxlength="24" type="number"/></div></td>
</tr>
</tbody>
单击链接/按钮时,我希望以相同的格式向表中添加一行,但数组增加 1:
<tbody>
<tr>
<td><div class="input text"><input name="data[OrderDetail][0][product_code]" maxlength="100" type="text"/></div></td>
<td><div class="input text"><input name="data[OrderDetail][0][product_name]" maxlength="255" type="text"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][0][product_qty]" step="any" type="number"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][0][product_price]" step="any" maxlength="24" type="number"/></div></td>
</tr>
<tr>
<td><div class="input text"><input name="data[OrderDetail][1][product_code]" maxlength="100" type="text"/></div></td>
<td><div class="input text"><input name="data[OrderDetail][1][product_name]" maxlength="255" type="text"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][1][product_qty]" step="any" type="number"/></div></td>
<td><div class="input number"><input name="data[OrderDetail][1][product_price]" step="any" maxlength="24" type="number"/></div></td>
</tr>
</tbody>
我可以使用普通的旧 Javascript 获得所需的结果,但我正在寻找更优雅的解决方案。我加载了 jQuery 和 JSHelper。
最佳答案
我的解决方案是这样的
$(":button").click(function() {
$("tr:last-child").clone().appendTo('tbody'); //clone the last row
$("tr:last-child input").each(function() { //for each input in the last row, do the following
var nameAttr = $(this).attr('name'); //get the whole value of attribute 'name'
var newIndex = parseInt(nameAttr.replace(/[^\d]/g, ''))+1; //get the digit and add one
$(this).attr('name',nameAttr.replace(/\d/,newIndex)); //replace the old digit with new
});
});
关于javascript - CakePHP 2.0 添加 html 表格行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9533657/