问题描述
大家好!
我有一个动态复选框,我用 jquery 来做,我的问题是当我尝试保存在我的数据库中时,这会保存我在一行中不同行上选择的所有复选框中的所有值,我使用 implode 来保存在单元格中,但在所有单元格上保存相同的结果,“medicamento”和“dosis”的输入文本正常工作,但复选框“cuando1”不起作用。
Jquery 脚本
<script id="document-template" type="text/x-handlebars-template">
<tr class="delete_add_more_item" id="delete_add_more_item">
<td style="width:300px;border: 5px solid transparent"><input type="text" class="form-control" name="medicamentos[]" aria-describedby="medicamentos" id="medicamentos" placeholder="Medicamentos Recetados"></td>
<td style="width:100px;border: 5px solid transparent"><input type="text" class="form-control" name="dosis[]" aria-describedby="dosis" id="dosis" placeholder="Dosis"></td>
<td style="width:50px;border: 5px solid transparent"><label><input type="checkBox" name="cuando[]" id="cuando1" value="Mañana"></label></td>
<td style="width:50px;border: 5px solid transparent"><label><input type="checkBox" name="cuando[]" id="cuando2" value="Tarde"></label></td>
<td style="width:50px;border: 5px solid transparent"><label><input type="checkBox" name="cuando[]" id="cuando3" value="Noche"></label></td>
<td>
<button type="button" class="btn btn-danger"><i class="fa fa-minus fa-2x removeaddmore" style="cursor:pointer;color:white;"></i></button>
</td>
</tr>
</script>
<script type="text/javascript">
$(document).on('click','#addMore',function(){
$('.table').show();
var source = $("#document-template").html();
var template = Handlebars.compile(source);
var data = {
medicamentos: medicamentos,dosis: dosis,cuando1: cuando1,cuando2: cuando2,cuando3: cuando3,}
var html = template(data);
$("#addRow").append(html)
});
$(document).on('click','.removeaddmore',function(event){
$(this).closest('.delete_add_more_item').remove();
});
</script>
Controller.PHP
$number = count($request->medicamentos);
for ($i=0; $i < $number; $i++) {
$cuando1 = implode(',',(array) $request->get('cuando'));
$Medicamentos = new Medicamentos();
$Medicamentos->idpaciente = $idpaciente;
$Medicamentos->medicamentos = $request->medicamentos[$i];
$Medicamentos->fecha = $hoy;
$Medicamentos->dosis = $request->dosis[$i];
$Medicamentos->cuando1 = $cuando1;
$Medicamentos->save();
}
带有选中复选框的刀片图像,可以看到选中的复选框已保存在数据库中的所有行上,并带有内爆。
我想为 aspirina 1: Mañana,Tarde 存钱,为 aspirina 2: Mañana 存钱,为 aspirina 3: Noche 存钱
- M = "Mañana"
- T = "Tarde"
- N = "Noche"
感谢您的帮助
解决方法
这是因为您获得了下面一行中复选框的所有值:
$cuando1 = implode(',',(array) $request->get('cuando'));
在您的 html 文件中,使用 cuando[]
而不是 cuando[i][]
,其中 i
从零开始并随着模板的每个循环递增。
然后在您的控制器中使用:
$cuando1 = implode(',(array) $request->cuando[$i]);