user1829823
user1829823

Reputation: 375

Prevent multiple form submission

I have a form for users to submit their reviews on films. When ever a field is missed a error alert will be displayed asking for the users to fill in the required field, but when you hit the submit button multiple times the required field alert error is displayed as many times at the button is pressed causing a long list of duplicated errors. How do I prevent this from happening? I have tried disabling the button on submit which works and display the errors once but then the button cant be pressed again. Any help would be greatly appreciated.

$('#review_a_film').submit(function (e) {

    var error = false;

    // No value for movie_title
    if ($('#movie_title').val() == "") {
        $('.error').append("<li>Please enter a title </li>");
        error = true;
    }

    // No Value for actor
    if ($('#leading_name').val() == "") {
        $('.error').append("<li>Please enter the leading actors name </li>");
        error = true;
    }

    // No value for rating
    if ($('#rating').val() == null) {
        $('.error').append("<li> Please enter a rating</li>");
        error = true;
    }

    //No value for review
    if ($('#review').val() == "") {
        $('.error').append("<li>Please enter a review</li>");
        error = true;
    }

    if (error) { // If error found dont submit.
        e.preventDefault();
    }
}); // End of .submit function: review_a_film.

Upvotes: 0

Views: 210

Answers (3)

Ed_
Ed_

Reputation: 19138

Why not just clear the .error list at the start of your submit function?

$('#review_a_film').submit(function (e) {

    var error = false;

    $('.error').empty();

    //...

}

Upvotes: 1

Anto Subash
Anto Subash

Reputation: 3215

you have disable the button and enable the button if there is any error.

$('#review_a_film').submit(function (e) {
$(this).attr('disabled',true);

var error = false;

// No value for movie_title
if ($('#movie_title').val() == "") {
    $('.error').append("<li>Please enter a title </li>");
    error = true;
}

// No Value for actor
if ($('#leading_name').val() == "") {
    $('.error').append("<li>Please enter the leading actors name </li>");
    error = true;
}

// No value for rating
if ($('#rating').val() == null) {
    $('.error').append("<li> Please enter a rating</li>");
    error = true;
}

//No value for review
if ($('#review').val() == "") {
    $('.error').append("<li>Please enter a review</li>");
    error = true;
}

if (error) { // If error found dont submit.
    e.preventDefault();
$(this).attr('disabled',false);
}
}); // End of .submit function: review_a_film.

Upvotes: 0

isherwood
isherwood

Reputation: 61114

You'll need to stop submit before validation, and then submit if it passes with something like:

$('#review_a_film').submit(function (e) {
    Event.stop(e);
    var form = Event.element(e);

    ...

    if (all is dandy) { form.submit() };
});

Upvotes: 1

Related Questions