jQuery document on submit
Asked Answered
H

1

6

I am using jQuery to post forms through ajax like this:

$(document).on("submit",this.id, function (e) {
    // Do stuff 
})

This way it takes the ID of the form and uses the ID to handle all the necessary things with the data from the different forms on different pages.

This works prefect with one form on the page. When I have multiple forms (with unique ID's) it fails, does not respond/trigger anymore.

I know I can enter the ID of the form myself and use multiple $(document).on... in my jQuery but I really like the approach I am using now.

Is there a way to solve this?

Haughty answered 23/3, 2014 at 11:32 Comment(2)
why not just use $('form').on('submit', function(e) {});? You can filter specific actions you need (the // Do stuff part) on $(this).prop('id')Seidel
@Seidel in some cases $('form').on binds right away when the page is loaded, so if you have dynamically generated content such as rendering elements in React, it will not be caught in this. Using $(document).on can capture elements rendered after page load.Brittani
E
16

You don't need to pass or use the ID, you probably have scope problem.

Use such code instead which is more flexible:

$(document).on("submit", "form", function (e) {
    var oForm = $(this);
    var formId = oForm.attr("id");
    var firstValue = oForm.find("input").first().val();
    alert("Form '" + formId + " is being submitted, value of first input is: " + firstValue);
    // Do stuff 
    return false;
})

Using the $(this) you get reference to the form being submitted, inside the event handler. You can then use it as you wish, instead of finding the form from scratch.

Live test case.

Elsworth answered 23/3, 2014 at 11:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.