Christian Dechery
Christian Dechery

Reputation: 880

Generic/Dynamic JQuery form submit

I have the following code to submit a form via jQuery and get its return (Json), process it and do some other stuff. It's working great.

$(function() {
   $('#update_marker').submit(function(e) {
    e.preventDefault();
    $.post($("#update_marker").attr("action"), $("#update_marker").serialize(), function(data) {

What I'd like to know if there is a way of handling lots of different forms with this without needing to create this block for each form id. Is there a way for the id, represented in the code by #update_marker to be dynamic (such as a parameter in a wrapper function) and so I would have only this one block of code for all my forms?

Upvotes: 2

Views: 891

Answers (2)

Dan F
Dan F

Reputation: 12051

Could it be as simple as swapping #update_marker for form?

$(function() {
    $('form').submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize(), function(data) {

This will hook every form element on your page. If you want it to only happen to certain forms, add a class="specialform" to them, then do something like

$(function() {
    $('.specialform').submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize(), function(data) {

Upvotes: 1

Yotam Omer
Yotam Omer

Reputation: 15376

If you would like to do the same actions on them why not use

$(function() {
       $('form').submit(function(e) {
        e.preventDefault();
        $.post($(this).attr("action"), $(this).serialize(), function(data) {...}
    });
});

Upvotes: 1

Related Questions