2016-05-31 12 views
0

我想讓我的ajax函數運行兩次,兩種不同的形式。我將一小段代碼加入了一個函數,現在我不知道如何爲一個不同的表單ID運行它。爲另一個ID變量運行JS函數

該行代碼是var form = $('#home-form');這是第一種形式,第二種形式的ID爲「popup-form」。

在粘貼它之後,我注意到表單發送後的模式會重新打開。你會提出什麼建議,只有當第一個表格被髮送時才能運行?

下面是函數...

function formAjax() { 
    // Get the form. 
    var form = $('#home-form'); 
    // Get the messages div. 
    var formMessages = $('#form-messages'); 
    // Set up an event listener for the contact form. 
    $(form).submit(function(e) { 
     // Stop the browser from submitting the form. 
     e.preventDefault(); 

     // Serialize the form data. 
     var formData = $(form).serialize(); 

     // Submit the form using AJAX. 
     $.ajax({ 
      type: 'POST', 
      url: $(form).attr('action'), 
      data: formData 
     }) 
     .done(function(response) { 
      // Make sure that the formMessages div has the 'success' class. 
      $(formMessages).removeClass('error'); 
      $(formMessages).addClass('success'); 

      // Set the message text. 
      $(formMessages).text(response); 

      // Clear the form. 
      $('#name').val(''); 
      $('#email').val(''); 
      $('#message').val(''); 

      // Pop-up Second Form 
      $("#sendForm").modal(); 

     }) 
     .fail(function(data) { 
      // Make sure that the formMessages div has the 'error' class. 
      $(formMessages).removeClass('success'); 
      $(formMessages).addClass('error'); 

      // Set the message text. 
      if (data.responseText !== '') { 
       $(formMessages).text(data.responseText); 
      } else { 
       $(formMessages).text('Oops! An error occurred and your message could not be sent.'); 
      } 
     }); 
    }); 
} 
formAjax(); 

回答

0
var forms = $('#home-form, #popup-form'); 

那麼你可能要像做

$.each(forms, function(){ 
    $(this).submit(function(e){ 
    // submit logic here 
    }); 
}); 
相關問題