Using preventDefault on a submit button

user2113538 picture user2113538 · Feb 27, 2013 · Viewed 20.9k times · Source

I am trying to solve a problem offered by a jQuery textbook. It reads like this

"The data is submitted even though no entries have been made, to fix this you must stop the default action of the submit button. To do that, code the preventDefault method of the event object in the if statement at the end of the file, as in figure 10-6

note* here's what the code looks like in 10-6 that's not working for me when I tag it on to the end of my code as the book suggests.

if (isValid == false) { event.preventDefault(); }

Remember that the name that you use for the event object must be the same as the name of the parameter that's used for the submit event handler.

note* the submit event handler looks like this

    $("#email_form").submit(
    function() {
        var isValid = true;

                      // the script proceeds to validate each text field accordingly                    bla bla bla

Now, test again with empty fields. This should display "This field is required" to the right of each field except the zip code field."

My problem is that my preventDefault is not working and it will still submit no matter what I try.

An interesting note from the text that explains figure 10-6 that may help, but that I don't quite understand is as follows.

"Here you see a final if statement that is true if the isValid variable is false, which means that one or more fields are invalid. In that case, the preventDefault method of the event object is executed. This object is passed to the function for the submit event handler as a parameter that's stored in the event variable by the first line in this handler. If you don't use the preventDefault method when one or more fields are submitted to the server, the form will be submitted to the server since that's its default action."

Any insight would be greatly appreciated.

Answer

helloandre picture helloandre · Feb 27, 2013

The event variable is something that must be passed to your handler. Your anonymous function function(){} needs to take in the event variable:

$("#email_form").submit(function(event){
    var isValid = true;

    // do all your validation here
    // potentially if one of the fields is empty 
    // isValid will be set to false

    if (!isValid) {
        event.preventDefault();
    }
});