簡體   English   中英

將復選框與相應的輸入字段分組

[英]Grouping a checkbox with a corresponding input field

我試圖找到一種方法來對復選框和輸入字段進行分組,以便用戶只能在選中復選框的情況下將數據輸入到該字段中。 我目前有一個生成的復選框字段(表中的值)和相應的輸入字段。

我目前的解決方案是:

    @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 的新手,所以我很難想出一個萬無一失的解決方法。

謝謝。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM