Reputation: 127
how to submit a form by js onclick event? I'm using Laravel 4.1.
I tried this code
@foreach ($items as $item)
<li>
{{ Form::checkbox('items', $item->id , $item->done, ['onClick'=> 'this.form.submit()']) }}
{{ $item->name }}
</li>
@endforeach
but I can't get what I want. at the controller I have the following code:
public function postIndex()
{
$id = Input::get('id');
echo $id;
}
by the way, in chrome console I got the following error:
Uncaught TypeError: Cannot read property 'submit' of null
Can anybody help me with this?
Upvotes: 1
Views: 9888
Reputation: 1618
As far as I know you should not have more than one tag in a view. I suggest you use ajax to trigger the submit event. However, you don't even have one form open tag but just a a checkbox.
I might need some more information but from what I understand you need to submit data to the controller when the checkboxes are clicked.
I would do it this way:
// Your view
<!-- CSRF Token -->
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<!-- ./ csrf token -->
@foreach ($items as $item)
<input type="checkbox" name="{{$item->id}}" id="{{$item->id}}" value="{{$item->done}}" class="checkbox_click">
@endforeach
<script type="text/javascript">
$(document).ready(function() {
$('.checkbox_click').click(function(){
var currentValue = $(this).attr("value");
$.ajax({
url: 'your/route',
method: 'post',
data: {id: currentValue, _token: $('input[name="_token"]').val()},
success: function(data){
alert(data);
},
error: function(){},
});
});
});
</script>
// Your controller
public function postIndex()
{
if (Request::ajax)
{
$id = Input::get('id');
return Response::json($id);
}
}
// Your routes.php
Route::post('your/route', YourController@postIndex);
Upvotes: 2