1

I am trying to generate a list of forms using a foreach loop. The forms are just item names that use POST to pass their id to my controller so they can be updated. I am using onclick="form.submit()" to get the action.

This works as expected when there is only one item in list.

@foreach($items as $item)
{{ Form::open(['url'=>'item/view', 'name'=>'itemView']) }}
{{ Form::hidden('id', $item->id ) }}
  <li><a href="#" onclick="itemView.submit()">{{ $item->name }}</a></li>
{{ Form::close() }}
@endforeach

However, as soon as the are >1 items I get a 'itemView.submt is not a function' error. I susoect this is because there are now duplicate form names.

QUESTION: How do I use the array index to make the form names unique?

I have tried this with no luck.

@foreach($items as $item)
{{ Form::open(['url'=>'item/view', 'name'=>'itemView[]']) }}
{{ Form::hidden('id', $item->id ) }}
  <li><a href="#" onclick="itemView[].submit()">{{ $item->name }}</a></li>
{{ Form::close() }}
@endforeach

I am sure it's possible, not sure how.

Thanks!

1 Answer 1

2

You should use function with onclick, for example:

@foreach($items as $key => $item)
    {{ Form::open(['url'=>'item/view', 'name'=>'itemView[]']) }}
    {{ Form::hidden('id', $item->id ) }}
        <li><a href="#" onclick="submitForm({{ $key }})">{{ $item->name }}</a></li>
    {{ Form::close() }}
@endforeach

But a better approach would be keeping all JS in JS files and to not mix PHP and JS as I'm showing in my repo:

<a href="#" class="js_link">{{ $item->name }}</a></li>

And JS could look like this:

$('.js_link').on('click', function(e) {
    $(this).closest('form').submit();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Went your recco, keeping JS and PHP separated. Works.

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.