我正在尝试找到一种将复选框和输入字段分组的方法,以便用户只能在选中该复选框的情况下将数据输入到该字段中。我目前有一个生成的复选框字段(表中的值)以及相应的输入字段。
我当前的解决方案是:
@foreach($labourTypes as $id => $name)
<div class="checkbox">
<label>
{!! Form::checkbox("labour_types[]", $id) !!} {{$name}}
</label>
{!! Form::input('number', 'required_labour_type_hours[]', '') !!}
</div>
@endforeach
并输入数据库:
$required_labour_hours = array_filter($required_labour_hours);
$required_labour_hours = array_values($required_labour_hours);
foreach(array_combine($labour_types, $required_labour_hours) as $labour_type => $hours) {
DB::table('required_labour_type')->insert([
'id' => null,
'labour_type_id' => $labour_type,
'required_labour_type_hours' => $hours
]);
}
这是我当前的解决方法,但如果用户要填写没有勾选相应复选框的输入字段,它不会阻止(并且会弄乱插入)。
这就是目前的样子:
我正在尝试找到一种方法,以便仅在选中相应的复选框时才允许输入,或者在插入之前将它们分组到一个数组中,并删除在输入之前未选中复选框的那些?一般来说,我对 laravel 和 php 很陌生,所以我很难想出一个万无一失的解决方法。
谢谢。
最佳答案
我会在前端使用 jQuery 来控制用户的输入。为了安全起见,我还会验证服务器端的数据。使用 jQuery,如果未选中复选框,您可以轻松地将输入字段设置为只读,并根据需要进行更新。此代码假定输入字段是 type="text"
之一。您可以轻松更新以支持多种输入类型。
jQuery(document).ready(function($) {
$('.checkbox').each(function() {
var cbox = $(this).find('input[type=checkbox]'),
inp = $(this).find('input[type=text]');
cbox.on('change', function(evt) {
if( $(this).is(':checked') )
inp.removeAttr('readonly');
else
inp.attr('readonly', true);
});
//init
if( ! cbox.is(':checked') )
inp.attr('readonly', true);
});
});
在服务器端,这就像检查复选框是否存在一样简单。如果未选中复选框,则在表单提交期间不会将其发送到服务器。所以使用类似的东西:
if( isset($_POST['some_checkbox']) ) {
//sanitize, validate, and save the value of the corresponding text field
} // else do nothing with this text field
关于php - 将复选框与相应的输入字段分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33657958/