2016-05-31 4 views
0

2つの異なるフォームに対して2回実行するためにajax関数を取得しようとしています。私は関数のコードを少しずつ作って、別のフォームIDでどのように実行できるのか分かりません。異なるID変数のJS関数を実行しています

そのコード行はvar form = $( '#home-form')です。これは、第2フォームの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 
    }); 
}); 
ような何かをしたい場合があります
関連する問題