如何在Laravel中使用Ajax保存复选框值?

时间:2019-06-17 10:13:39

标签: javascript ajax laravel

我正在尝试将复选框的值保存在laravel中。我可以保存所有文本字段,并且所有代码都有效。当我尝试保存复选框的值时,代码中断。这是我尝试过的。感谢所有帮助。

这是我的控制人

public function addTodo(Request $request)
{
    $status = Todo::has('status') ? true: false;

    $todo = new Todo;
    $todo->item = $request->item;
    $todo->description = $request->description;
    $todo->status = $request->status;
    $todo->save();
    return response()->json($todo);
}

这是我的HTML

<div class="form-group">
    <div class="col-sm-10">
        <input type="checkbox" name="status" id="status" value="1"
              placeholder="Your description Here" required>
        </div>
    </div>
</div>

这是我的脚本

$(document).on('click','.create-modal', function() {
    $('#create').modal('show');
    $('.form-horizontal').show();
    $('.modal-title').text('Add Item');
});

$("#add").click(function() {
    $.ajax({
        type: 'POST',
        url: '/addTodo',
        data: {
            '_token': $('input[name=_token]').val(),
            'item': $('input[name=item]').val(),
            'status':$('input[name="status[]:checked'].val()
        },
        success: function(data){
            if ((data.errors)) {
                $('.error').removeClass('hidden');
                $('.error').text(data.errors.item);             

            } else {
                $('.error').remove();
                $('#table').append("<tr class='post" + data.id + "'>"+
                "<td>" + data.id + "</td>"+
                "<td>" + data.item + "</td>"+
                "<td>" + data.status + "</td>"+    
                "<td><button class='show-modal btn btn-info btn-sm' data-id='" + data.id +
                        "' data-item='" + data.item + "' data-status='" + data.status + "'> +
                            <span class='fa fa-eye'></span></button> +
                    <button class='edit-modal btn btn-warning btn-sm' data-id='" +
                        data.id + "' data-item='" + data.item + "' data-status='" +
                        data.status + "'><span class='glyphicon glyphicon-pencil'></span></button> + 
                    <button class='delete-modal btn btn-danger btn-sm' data-id='" + 
                        data.id + "' data-item='" + data.item + "' data-status='" + data.status +
                         "'><span class='glyphicon glyphicon-trash'></span></button> +
                </td>"+ "</tr>");
            }
        },
    });

    $('#item').val('');
    $('#status').val('');
    location.reload();

});

1 个答案:

答案 0 :(得分:2)

尝试

$('input[name="status"]:checked').val()