jQuery - Скрыть форму при отправке - PullRequest
1 голос
/ 23 июля 2011

Я хотел бы скрыть свою форму при успешной отправке:

Вот ссылка на тестовое пространство: http://www.bgv.co.za/testspace/contact_3.php

Это комбинация PHP jQuery mongrel.В настоящее время я использую валидатор jQuery и добавил собственный скрипт для изменения класса в полях ввода, оборачивая div - как способ отображения обязательных полей.

Вот что у меня есть в PHP

<?php

$ subject = "Запрос формы контакта с веб-сайтом";

// Если форма отправлена ​​if (isset ($ _ POST ['submit']))) {

//Check to make sure that the name field is not empty
if(trim($_POST['contactname']) == '') {
    $hasError = true;
} else {
    $name = trim($_POST['contactname']);
}

//Check to make sure sure that a valid email address is submitted
if(trim($_POST['email']) == '')  {
    $hasError = true;
} else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) {
    $hasError = true;
} else {
    $email = trim($_POST['email']);
}

//Check to make sure comments were entered
if(trim($_POST['message']) == '') {
    $hasError = true;
} else {
    if(function_exists('stripslashes')) {
        $comments = stripslashes(trim($_POST['message']));
    } else {
        $comments = trim($_POST['message']);
    }
}

//If there is no error, send the email
if(!isset($hasError)) {
    $emailTo = 'info@bgv.co.za'; //Put your own email address here
    $body = "Name: $name \n\nEmail: $email \n\nComments:\n $comments";
    $headers = 'From: My Site <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;

    mail($emailTo, $subject, $body, $headers);
    $emailSent = true;

}

}?>

и вот область скрипта:

$(document).ready(function(){
$('#contactform').validate({
        showErrors: function(errorMap, errorList) {

            //restore the normal look
            $('#contactform div._required').removeClass('_required').addClass('xrequired');

            //stop if everything is ok
            if (errorList.length == 0) return;

            //Iterate over the errors
            for(var i = 0;i < errorList.length; i++)
                $(errorList[i].element).parent().removeClass('xrequired').addClass('_required');
        }

});});

Таким образом, в тот момент, когда кто-то отправляет действительную форму, вы видите новый заголовок прямо под контактной формой - отсюда:

        <?php if(isset($emailSent) && $emailSent == true) { //If email is sent ?>
    <h1 class="success_form">Thank You!</h1>
    <?php } ?>  

и под ним - данные, введенныеформа.

Но ниже приведена форма, которую я хочу скрыть .... Пожалуйста, помогите:)

Вот новый бит, который я добавил благодаря Flashbackzoo

        $("#content").empty();
    $("#content").append(
    "<p>If you want to be kept in the loop...</p>" +
    "<p>Or you can contact...</p>"
    );
    $('h1.success_').removeClass('success_').addClass('success_form');
    $('#contactform').hide();

},

1 Ответ

2 голосов
/ 23 июля 2011

Добавить обработчик отправки ...

$('#contactform').validate({
    showErrors: function(errorMap, errorList) {
        // your code...
    },
    submitHandler: function() {
        $('#contactform').hide();
    }
});

UPDATE

В ответ на ваш комментарий Бретт. Вы можете изменить свой submitHandler на что-то вроде ...

submitHandler: function() {
    $("#content").empty();
    $("#content").append(
        "<p>If you want to be kept in the loop...</p>" +
        "<p>Or you can contact...</p>"
    );
}

Это удалит все дочерние элементы из #content с помощью метода .empty (). Затем добавьте элементы в #content с помощью метода .append (). Вы можете поменять #content на любой понравившийся селектор.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...