charlie
charlie

Reputation: 481

JQuery function on form submit

I have this JQuery function:

function CheckRequired() {
    alert("test");

    var ret = true;

    $(".required").each( function() {
        var check = $(this).val();

        if(check == '') {
            //alert($(this).attr("id"));
            event.preventDefault();
            ret = false;
        }
    });

    if(!ret) {
        alert("One or more fields cannot be blank");
        return false;
    }
}

which checks for all input fields with a class of required

i have many forms on on my site and i do not call this function on every form.

is there a way i can do this on every form submit without adding any extra code to each form?

Upvotes: 0

Views: 50

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30557

Use event delegation with jQuery on()

$(document).on('submit', 'form', CheckRequired);

Also, if you wish to use CheckRequired instead of an anonymous function, be sure to modify its decleration to accept the event parameter

function CheckRequired(event) {...}

Upvotes: 2

Related Questions