[英]Looping Table Rows in Form
所以我正在尝试编写一个表单,该表单位于只有一行的表格中。 该行包含一个下拉框、文本框和一个复选框。
<table class="table text-size-12">
<thead>
<tr>
<th scope="col">Location</th>
<th scope="col" class="text-nowrap">COD Charge</th>
<th scope="col">Allow Negotiate</th>
</tr>
</thead>
<tbody>
<?php
for($rows = 0; $rows < 5; $rows++):
?>
<tr>
<td>
<select name="location" class="form-control" style="width:250px">
<option value="">--- Select Location ---</option>
<?php foreach ($locations as $state): ?>
<optgroup label="--- <?= $state->name ?> ---">
<?php foreach ($state->locations as $area): ?>
<option value="{{ $key }}"><?= $area->name ?></option>
<?php endforeach ?>
</optgroup>
<?php endforeach ?>
</select>
</td>
<td>
<input type="text" id="shipping_fee_value">
</td>
<td>
<input type="checkbox" id="shipping_fee_allow_negotiate">
<script>
document.getElementById('shipping_fee_allow_negotiate').onchange = function (){
document.getElementById('shipping_fee_value').disabled = this.checked;
}
</script>
</td>
</tr>
<?php endfor ?>
</tbody>
</table>
如您所见,我使用了 Javascript,因此如果选中该复选框,则文本框将被禁用。
<td>
<input type="text" id="shipping_fee_value">
</td>
<td>
<input type="checkbox" id="shipping_fee_allow_negotiate">
<script>
document.getElementById('shipping_fee_allow_negotiate').onchange = function (){
document.getElementById('shipping_fee_value').disabled = this.checked;
}
</script>
</td>
而且我还使用for
将行循环了 5 次。 我的问题是,禁用文本框脚本的复选框仅适用于第一行,如何让每一行独立?
PS 我不喜欢硬编码每个特定的行只是因为这样。
您正在重复元素的 id。 你不能这样做。 id 是唯一的。 在每个元素上设置一个唯一的 id。
<td>
<input type="text" id="shipping_fee_value_<?= $rows ?>">
</td>
<td>
<input type="checkbox" class="shipping_fee_allow_negotiate" data-target="shipping_fee_value_<?= $rows ?>">
<script>
var elements = document.getElementsByClassName('shipping_fee_allow_negotiate');
for (var i = 0; i < elements.length; i++) {
elements[i].onchange = function() {
document.getElementById(this.dataset.target).disabled = this.checked;
}
}
</script>
</td>
这里我们使用$row
变量为输入的id
属性添加索引。
<input type="text" id="shipping_fee_value_0"/>
我们还使用复选框上的data-target
属性来告诉他在onchange
回调中处理哪个特定输入。
<input type="checkbox" class="shipping_fee_allow_negotiate" data-target="shipping_fee_value_0">
最后分配回调的选择器使用 getElementsByClassName 来选择所有复选框。
因为您的 id 很常见,这就是为什么他们只考虑第一行而不是 common id 使用动态 id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.