首页 > 解决方案 > 带有laravel刀片模板循环和总和的javascript

问题描述

我正在尝试使用 java 脚本对我的表进行计算,但我不知道如何将它与其余的 id 循环。现在我只能计算单个项目如何使这个倍数这里是结果在此处输入图像描述

如您所见,只有 id 1 得到结果,而 id 2 为 null 我怎样才能使这项工作在这里是我的 java 脚本

function calc(){     
         var n1 = parseFloat(document.getElementById('n1').value);
         var n2 = parseFloat(document.getElementById('n2').value);
         var oper = document.getElementById('result').value = n1*4+n2; 
}

  <table id="my-table" class="table table-hover table-bordered">
                <thead>
                    <tr >
                      <th class="text">NAME</th>
                      <th class="text">A/P</th>
                      <th class="text">H/W</th>
                      <th class="text">Result</th>
                    </tr>
                 </thead>
                 <tbody>
                 @foreach($scores as $index => $score) 
                 <tr> 
                 <td>{{$score->lead->student_name}} <input type="hidden" name="scores[{{$loop->index}}][id]" value="{{$score->id}}"></td> 
                 <td style="text-align:center"><input id="n1" type="text" name="scores[{{$loop->index}}][jan_ap]" value="{{$score->jan_ap}}" class="input" autocomplete="off"></td> 
                 <td style="text-align:center"><input id="n2" type="text" name="scores[{{$loop->index}}][jan_hm]" value="{{$score->jan_hm}}"  class="input" autocomplete="off"></td> 
                 <td style="text-align:center"><input id="result" type="text" name="scores[{{$loop->index}}][result]" value="{{$score->result}}"  class="input" autocomplete="off"></td> 
                 </tr> 
                 @endforeach
                </tbody>
                </table><div class="form-group ">
                <button onclick="calc(); " type="submit">Submit</button>
                </div> 

标签: javascriptphplaravelfor-loop

解决方案


从聊天讨论和您的控制器代码中发现,您想要添加带有一些公式的行并将结果保存results在数据库中的字段中。所以在这里我们提出了代码

控制器保存方法

$scores = $request->input('scores');

foreach($scores as $row){ 
    $score = Score::find($row['id']); 
    $score->jan_ap = $row['jan_ap']; 
    $score->jan_hm = $row['jan_hm']; 
    $score->result = round($row['jan_ap'] * 0.5) + ($row['result'] * 0.5); 
    $score->save(); 
}

注意:从刀片模板中删除您的结果文本输入,因为它不再使用。


推荐阅读