wiseman7687
wiseman7687

Reputation: 175

jQuery prevent all forms from submitting at one time

I have a set of HTML form links which I am submitting upon click which have the id "ajaxForm"

    for ($year = 2008; $year <= intval(date('Y')); $year++) {
    if ($year == $currentYear)
        continue;
    echo '<div style="float:right;padding-right:20px;"><form name="year' . $year . 'Form1" id= "ajaxForm" action="/managementDashboard#visibleTab-5" method="post"><input name="getRecordsFor" type="hidden" value="' . $year . '"><a id="buttonRed" href="javascript:document.year' . $year . 'Form1.submit();">' . $year . '</a></form></div>' . chr(10);
}

However instead of default submission I use jQuery to post the data with this:

        jQuery("form#ajaxForm").click(function(event) {

        /* stop form from submitting normally */
        event.preventDefault(); 

        /* Send the data using post and put the results in a div */
        jQuery.post( '/ajaxFunctions?mgmtDbrdPge=5', jQuery("#ajaxForm").serialize(),
        function( data ) {
            jQuery( "#visibleTab-5" ).empty().append( data );

        }
    );
    });

The problem is that it is submitting ALL the forms instead of the individual one I click. Is there a way I can prevent this without having to write jQuery link for each individual form?

UPDATE - I accepted one of the answers because his method is legitimate but I realized what my issue was. Instead of jQuery("#ajaxForm").serialize(), I should have had it written as jQuery(this).serialize() to only call upon the data that was submitted with the click instead of ALL the forms with that id.

Upvotes: 1

Views: 494

Answers (1)

Sushanth --
Sushanth --

Reputation: 55740

Looks like you are having more than one form with the same id of ajaxForm . Make sure it is unique

If you know the id's of the Ajax forms in your page.. then you can do this

jQuery("form#ajaxForm ,form#myForm , form#myFormThird ").click(function(event) {

This will make sure the multiple elements are attached to the same event handler..

UPDATED CODE If you do not know the id's then you can iterate using a for loop and attach the events..

$('form').each(function() {

    $(this).click(function(event) {

       // Your Function
    }
});

Also make sure you use .on() to attach your events .. Instead of just the click so that the events are delegated..

jQuery("form#ajaxForm").on('click',function(event) {

Upvotes: 3

Related Questions