簡體   English   中英

如何使用Laravel和Ajax從數據庫陣列中選中復選框

[英]How to get checkbox checked from database array using Laravel and Ajax

我正在嘗試將數據從數據庫獲取到已選中的復選框。 數據庫中的復選框數據是使用json插入的數組,它們是基於insert函數的動態數據。

我的任務表:

id |employee_id | startDate  | endDate   | ...
---|------------|------------|-----------|--------
1  |["1","2"]   | .......... | ..........| ....

我的TasksController.php

function fetchdata(Request $request)
    {
        $id = $request->input('id');
        $task = Task::find($id);
        $output = array(
            'employee_id'    =>  $task->employee_id,
            'name'    =>  $task->name,
            'description'    =>  $task->description,
            'startDate'    =>  $task->startDate,
            'endDate'    =>  $task->endDate,
            'percentage'    =>  $task->percentage       

        );
        echo json_encode($output);
    }

    public function getEmployeesList()
    {

        $employeesList = Employee::all();


        return view('adminlte::tasks', ['employeesList' => $employeesList]);


    }

我的tasks.blade.php

 @foreach($employeesList as $emplist)
    <label class="checkbox-inline">
      <input type="checkbox" id="employee_id" name="employee_id[]" class="chck" value="{{$emplist->id}}" >{{ $emplist->name }}</label>    
 @endforeach

我在刀片內的Ajax功能:

$(document).on('click', '.edit', function(){
        var id = $(this).attr("id");
        $('#form_output').html('');
        $.ajax({
            url: "{{route('tasks.fetchdata')}}",
            method: 'get',
            data: {id:id},
            dataType: 'json',
            success:function(data)
            {
                $('#id').val(data.id);
                $('#employee_id').val(data.employee_id);
                $('#name').val(data.name);
                .......................
                ..................
            }
        })
    });

因此,如何檢查已選中的數據庫和復選框中的數據,因為現在在嘗試更新記錄時,我會得到空的“ employee_id”值。

先感謝您

由於您是在服務器端對數據進行編碼,因此必須在客戶端進行解碼,例如:

...
success:function(data)
{
    console.log( data );
    data = JSON.parse(data);

    $('#id').val(data.id);
    $('#employee_id').val(data.employee_id);
    $('#name').val(data.name);
    ...

}

暫無
暫無

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

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