【问题标题】:Grouping a checkbox with a corresponding input field将复选框与相应的输入字段分组
【发布时间】:2016-02-12 23:33:14
【问题描述】:

我正在尝试找到一种方法来对复选框和输入字段进行分组,以便用户只有在选中复选框时才能将数据输入到字段中。我目前有一个带有相应输入字段的生成复选框字段(表中的值)。

我目前的解决方案是:

    @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
        ]);
    }

这是我目前的解决方法,但如果用户要填写一个没有勾选相应复选框的输入字段,它不会阻止(并且会导致插入混乱)。

这就是现在的样子:

http://i.imgur.com/sVhnFMc.png

我正在尝试找到一种方法,以便仅在选中相应的复选框时才允许输入,或者在插入之前将它们分组到一个数组中,并在输入之前删除没有选中复选框的那些?我一般是 laravel 和 php 的新手,所以我很难想出一个万无一失的解决方法。

谢谢。

【问题讨论】:

    标签: php mysql forms validation laravel


    【解决方案1】:

    我会在前端使用 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
    

    【讨论】:

    • 我目前正在处理我的应用程序的另一部分,所以我还没有开始验证数据服务器端,但是 jQuery read 只做了我需要的。谢谢。
    猜你喜欢
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 2021-03-03
    • 1970-01-01
    • 2013-04-24
    • 2014-08-14
    • 1970-01-01
    相关资源
    最近更新 更多