Reached's avatar

Submit dynamic form ajax

Hi guys,

I have a form that I want to create inside a foreach loop, so potentially there can be many forms on each page.

How do I distinguish between these dynamic forms in my jQuery code?

Right now they all get the same data-attribute, which means that when I submit the form, it submits all forms with the same data attribute..

My JS:

$('form[data-remote]').on('submit', function(e) {
        e.preventDefault();

        var form = $(this);

    ... (removed for brevity)
});

My HTML:

... Foreach up here ...
<form class="addColorsForm" method="POST" action="/colors/add" data-remote>
                        {{ csrf_field() }}
                        <input type="text" name="color_value" placeholder="Insert value">
                        <input type="hidden" name="board_id" value="{{ $board->id }}">
                        <input type="hidden" name="group_id" value="{{ $colorGroup->id }}">
                        <input type="submit" class="submitButton">
                    </form>
0 likes
5 replies
bobbybouwmann's avatar

You should catch the click event of the button from the form. This was you can trigger only the parent form

Reached's avatar

Hey @bobbybouwmann,

$('input[type=submit]').on('click', function(e) {
        e.preventDefault();

        var form = $(this).parent();

        console.log(form);

If I do the above, it console.logs both forms out, how do I become more specific than this?

jekinney's avatar

Technically with jquery you don't need a form element, though HTML wise it's good practice. Make the foreach inside one form and use inputs and submit as one form. In side a form element you can put other HTML besides labels, inputs and buttons.

1 like

Please or to participate in this conversation.