I’m trying to save the value of the check box in laravel. I can save all the text fields and all the code works. When I try to save the value of the checkbox the code breaks. Here is what I’ve tried. All the help is appreciated.
Here is my controller I’ve
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); }
Here is my 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>
Here is my script
$(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(); });
Advertisement
Answer
try this
$('input[name="status"]:checked').val()