首页 > 解决方案 > 复选框 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 ......

标签: javascriptphplaravel

解决方案


你有这种行为是因为你覆盖的每个循环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>


推荐阅读