javascript - 复选框 id 没有在 laravel 中正确分配
问题描述
在我的 laravel 应用程序中,我在表单中加载了一组复选框
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test List :</strong>
<br>
@foreach($ttype as $value)
<label>{{ Form::checkbox('samp_list[]', $value->test_name, false, array('class' => 'name','sumT'=>''.$value->test_desc.'','id'=>'cbox'.$value->id.'','onclick'=>'myFunction()')) }}
{{ $value->test_name }}</label>
<script type="text/javascript">
function myFunction() {
var boxId=<?php echo''.$value->id.''; ?>
console.log('cbox'+boxId);
// Get the checkbox
var checkBox = document.getElementById('cbox'+boxId);
// Get the output text
var text = document.getElementById("text");
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
text.style.display = "block";
alert('puka');
} else {
text.style.display = "none";
}
}
</script>
<br/>
@endforeach
</div>
</div>
在该代码中,我试图将一个复选框 id 分配给 javascript 的 boxId 变量。我通过数据库获取所有这些复选框值,即使我已经在我的 foreach 循环中包含了 javascript 代码,但只有最后一个复选框 id 存储为 boxId。
如果我选择复选框 1 boxId 应该是 cbox1 如果它是复选框 2,boxId 必须是 cbox2 ....如果我选择第 10 个复选框,那么 boxId 必须是 cbox10 ...
但现在至于我的 boxId,我只得到最后一个复选框 id ......
解决方案
你有这种行为是因为你覆盖的每个循环myFunction
。
您可以做的是移出myFunction
循环,将事件作为参数传递并从事件中获取复选框event.target
。那样的东西...
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test List :</strong>
<br>
@foreach($ttype as $value)
<label>{{ Form::checkbox('samp_list[]', $value->test_name, false, array('class' => 'name','sumT'=>''.$value->test_desc.'','id'=>'cbox'.$value->id.'','onclick'=>'myFunction(event)')) }}
{{ $value->test_name }}</label>
<br/>
@endforeach
<script type="text/javascript">
function myFunction(event) {
// Get the checkbox
var checkBox = event.target;
// Get the output text
var text = document.getElementById("text");
// If the checkbox is checked, display the output text
if (checkBox.checked == true){
text.style.display = "block";
alert('puka');
} else {
text.style.display = "none";
}
}
</script>
</div>
</div>
推荐阅读
- anylogic - Anylogic:使用 Logging 跟踪 AGV 距离
- python - 如何在测试运行时类型检查期间模拟 Python 类?
- python - 如果行数与标题数不匹配,则在 read_csv 中引发错误
- swagger - 如何避免 OpenAPI 文档中的重复端点
- python - 使用 python 的 requests 模块获得与 curl -v 相同的结果
- excel - 使用 excel 文件运行数据驱动测试 (MSTest) 的问题
- postgresql - 使用具有不同 order by 子句的 postgres 窗口函数
- java - Java 无法识别 DataType 20(版本 1.15.0)
- batch-file - 在 for 循环中调用变量 - BATCH
- c - 如果服务器正在侦听 v6 套接字且 IPV6_V6 选项设置为 false,如何识别接收到的连接是 v4 还是 v6