afreeland
afreeland

Reputation: 3979

Select form children when multiple forms are present jQuery

I am dealing with a webpage that has multiple forms..some basic HTML forms and some AJAX forms. I have a created validation for inputs, let me give an example...if an input has a class="required" whenever a submit button is pressed if any required classes are empty then the form doesnt submit. Which works great...until you have multiple forms with required fields that dont apply to the section your submitting.

I am able to find the closest form $(this).closest("form") and it gets me the form element properly, I then need to be able to loop only through the children of that form. I have tried: .children(':input'), .find('input') and honestly to many to list.

Here is the code for when a button is selected

$('#formSubmit').click(function (e) {
        var submit = true;
        var form = $(this).closest("form");
        var formID = $(form).attr("id");
        e.preventDefault();

        $(form).children(":input").each(function () {
            if ($('#ERROR').length > 0) {
                submit = false;
                alert("Please fix errors to continue");
            }
            $('.required').each(function () {
                if ($(this).val() == "" || $(this).val() == undefined) {
                    submit = false;
                    $(this).css({ 'background-color': '#fef236' });
                }
            });
        });
        if (submit == true) {
            this.form.submit();
        }
    }); //End of #formSubmit

Also of interest I have started creating forms with ids that are GUID's so they will be unique and allow me to target things without any issues, just wanted to throw that out there if it can help lead to a solution

I appreciate any help =)

Upvotes: 1

Views: 1769

Answers (1)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

$(this).closest("form").find(":input") is a correct way to find all the inputs. I think the problem lies in $('.required'). That call starts the search again from the global level, thus finding inputs from all forms on the page.

I don't see the need to do .find(":input") in the first place. Just get the required fields with form.find(".required") and loop through those.

Upvotes: 2

Related Questions