himynameis himynameis - 2 months ago 7
HTML Question

Form Validation with Success

When I submit the form without filling in any information it quickly displays the error message then fades. I only want the form to fade if there's no error messages and the validation is successful. I think I may need to use an if statement for success or something to do with a submit handler?

So far I have this - https://jsfiddle.net/wnmLmcm8/

$(document).ready(function () {

$("form").submit(function (e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: {
name: $('#name').val(),
email: $('#email').val()
},
success: function () {
$('#emailform').fadeOut("slow");
}
});
});

$("form").validate({
rules: {
email: {
required: true,
email: true,
remote: "http://localhost:3000/inputValidator"
}
}
});
});

Answer

Here is a working version of your jsFiddle: https://jsfiddle.net/ywhpdLen/3/

This snippet works, based off of your jsFiddle, but your jsFiddle does not work. I had to pull the code into my own dev environment, locally.

The popup stays until you click in the text field.

Adding "required" to the input elements & using the default ".validate()" extension does the job. If you're looking to customize it, I'd highly recommend looking at https://jqueryvalidation.org/documentation/

<div id="emailform">
    <form method="post" action="form.php">
        <hr>
        <label for="name">Name</label>
        <br>
        <input type="text" name="name" id="name" class="NewsLetter1" required/>
        <br>
        <label for="email">Email</label>
        <br>
        <input type="text" name="email" id="email" class="NewsLetter2" required/>
        <input type="submit" value="Submit">
        <hr>
    </form>
</div>

<script>
    $(document).ready(function () {

        $("form").submit(function (e) {
            e.preventDefault();
            $.ajax({
                type: this.method,
                url: this.action,
                data: {
                    name: $('#name').val(),
                    email: $('#email').val()
                },
                success: function () {
                    $('#emailform').fadeOut("slow");
                },
                failure: function (ex) {

                }
            });
        });

        $("form").validate();
    });

</script>