1

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?

1
  • Is this inside a form ? Commented Jun 15, 2014 at 22:17

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.