Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery document on submit

Tags:

jquery

submit

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?

like image 416
Klaaz Avatar asked Mar 23 '14 11:03

Klaaz


1 Answers

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.

like image 103
Shadow Wizard Hates Omicron Avatar answered Oct 01 '22 23:10

Shadow Wizard Hates Omicron