1

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!

0

2 Answers 2

1

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;

});
Sign up to request clarification or add additional context in comments.

1 Comment

i tried! it requires 15 reputation to upvote and this is my first question :/ sorry... but thanks!! :D
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.