为不同的ID变量运行JS函数

时间:2016-05-31 14:48:35

标签: javascript php jquery ajax forms

我试图让我的ajax函数运行两次,用于两种不同的形式。我把一些代码变成了一个函数,现在我不知道如何为不同的表单id运行它。

这行代码是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();

1 个答案:

答案 0 :(得分:0)

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

然后你可能想做类似

的事情
$.each(forms, function(){
  $(this).submit(function(e){
     // submit logic here
  });
});
相关问题