jQuery ajax表单在没有错误时不提交

时间:2017-09-13 09:47:05

标签: javascript jquery html phpmailer ajaxform

我使用jQuery& PHPMailer的()。如果存在错误,则它们将显示在表单上方,例如“名称是必填字段”,但是当正确填写所有字段时,表单仍会在顶部显示空的alert alert-danger框并且不提交。 / p>

的jQuery

var form = jQuery("#contact-form");
form.submit(function(e) {
    e.preventDefault();
    jQuery('#submit').attr("disabled", true);
    jQuery.ajax({
        url:      '/process-contact.php',
        type:     'POST',
        data:     form.serialize(),
        dataType: 'json'
    }).done(function(data) {
        jQuery('#messages').removeClass();
        if (data.code === 1) {
            form[0].reset();
            jQuery('#messages').addClass('alert alert-success');
            jQuery('#submit').attr("disabled", false);
        } 
        else {
            jQuery('#messages').addClass('alert alert-danger');
            jQuery('#submit').attr("disabled", false);
        }
        jQuery('#messages').html(data.message);
        jQuery('html, body').animate({
            scrollTop: jQuery("#messages").offset().top
        }, 1000);
    });
});

HTML

<form class="contactForm" id="contact-form" name="contact-form">
    <div class="row">
        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
            <div class="form-group">
                <label for="name">Name</label> 
                <input class="form-control" id="name" name="name" placeholder="Your Name" type="text">
            </div>
            <div class="form-group">
                <label for="email">Email Address</label>
                <input class="form-control" id="email" name="email" placeholder="Your Email" type="text">
            </div>
            <div class="form-group">
                <label for="subject">Subject</label>
                <input class="form-control" id="subject" name="subject" placeholder="Subject" type="text">
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
            <div class="form-group">
                <label for="name">Message</label>
                <textarea class="form-control" name="message" placeholder="Message"></textarea>
            </div>
        </div>
        <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
            <button class="btn btn-skin pull-right" name="submit" id="submit" type="submit">Send Message</button>
        </div>
    </div>
</form>

1 个答案:

答案 0 :(得分:0)

每次点击后删除课程alert-danger

form.submit(function(e) {
 jQuery('#messages').removeClass('alert-danger');
 ........