0

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?

1 Answer 1

2

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) {...}
Sign up to request clarification or add additional context in comments.

8 Comments

That's just event binding, not delegation.
i just added this code and at the top of the CheckRequired function i added alert("test") - then when i submit a form its not showing
Still need to pass event to support FF and btw, should check inside CheckRequired() only for inputs inside specific FORM
@charlie So replicate your issue online (e.g on jsFiddle) so we can see what's going wrong
@A.Wolff, silly question, but how would we pass the event in this case? CheckRequired, event... ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.