Waldir Bolanos
Waldir Bolanos

Reputation: 423

JQuery: Reusing submit function

Hey guys i have looked as much as i could and i could not find an answer, i am creating an admin interface that has forms all over the place and i would like to use the same jquery code for all of them, i have some code that is getting the job done but i would like to know if there is a more efficient way to do it. here is the code

    function submitForm( formname ) 
{
  $.ajax
  ({
    type:'POST', 
    url: 'session.php', 
    data: $(formname).serialize(), 
    success: function(response) 
    {
      if( $('#message_box').is(":visible") ) 
      {
        $('#message_box_msg').html ('') 
        $('#message_box').hide();
      }
      $('#message_box').slideDown();
      $('#message_box_msg').html (response);      
    }
  });
return false;
}

Now my forms look something like this:

<form id="adminForm" action="session.php" method="post" onsubmit="return submitForm('#adminForm');">

Now my question is... is there a simpler way to do this, like without having to provide the submitForm() function with the form id every time?

Thanks in advance!

Upvotes: 1

Views: 172

Answers (2)

charlietfl
charlietfl

Reputation: 171669

You may want to delegate a handler to document or other permanent asset in the page(s) to account for any ajax loaded forms. This will replace your inline onsubmit

$(document).on('submit','form', function(){ 

     var allowSubmit=false,
         noSubmitMessage="Can't submit", /* can change message in various places in following code depending on app*/
         $form=$(this);/* cache jQuery form object */
    if( $form.hasClass('doValidation')){
        /* class specific code to run*/    
        allowSubmit = validationFunction();
    }

    if( allowSubmit){
       var data=$form.serialize()          
       /* do ajax*/
    }else{
       /* user feedback*/ 
       alert( noSubmitMessage);
    }

return false;

});

Upvotes: 1

WhyNotHugo
WhyNotHugo

Reputation: 9926

Yes, define a common class for all your forms, and use

$(".form_class").submit(function() {

  //stuff that gets executed on form submission ...

  return result;
})

And dump the inline "onsubmit". It's also cleaner to do this in general, as it separated view from behaviour.

Upvotes: 1

Related Questions