event.preventDefault();只在部分时间提交表格

时间:2014-12-01 23:06:48

标签: javascript forms javascript-events

我正在使用Mailchimp API提交表单。目标是防止Mailchimp提供的默认回调。大多数时候,event.preventDefault()的行为都应该如此。然后随机它将无法工作:

$(function () {
 var $form = $('#mc-embedded-subscribe-form');
 $('#mc-embedded-subscribe').on('click', function(event) {
     if(event) event.preventDefault();
    register($form);
   });
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
        if (data.result != "success") {
            // Something went wrong, do something to notify the user. maybe alert(data.msg);
            var message = data.msg
            var messageSh = data.msg.substring(4);
            if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single @') {
               $('#notification_container').html('<span class="alert">'+messageSh+'</span>'); 
            } else {
                $('#notification_container').html('<span class="alert">'+message+'</span>');
            }
        } else {
            // It worked, carry on...
        var message = data.msg;
        $('.popup-promo-container').addClass('thanks');
        $('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
        $('.complete-promo').html(message).removeClass('hidden');
        setTimeout(function() {
            document.querySelector('.popup-promo').style.display = "none";
        },20000);

        }
    }
});
}

1 个答案:

答案 0 :(得分:1)

<强>尝试

  1. 脱掉准备好的功能。
  2. 删除if on event
  3. 代码:

    var $form = $('#mc-embedded-subscribe-form');
    
    $('#mc-embedded-subscribe').on('click', function(event) {
        event.preventDefault();
        register($form);
    });