简体   繁体   中英

JQuery Validation - dynamic fields seem to break validation

I have this:

<div id="FormContainer">

    <button type="button" data-action="PrintWeightRange">Add Weight Range</button>

    <form id="DynamicForm" action="php/printinputs.php" method="POST">
        <!-- Fields are loaded in via JQuery and AJAX -->
    </form>

</div>

Other functions append inputs and buttons to the form. When the submit button is clicked, a function bound by JQuery appends fields to the form.

The form looks like this when populated:

<div id="FormContainer">

<button type="button" data-action="PrintWeightRange">Add Weight Range</button>

<form id="DynamicForm" action="php/printinputs.php"
method="POST">

    <button type="button" data-action="FormSubmit">Submit</button>

    <fieldset data-purpose="ShippingMethodDetails">
        <input type="text" value="Express Shipping" data-purpose="ShippingMethodName">
        <select data-purpose="ShippingMethodType">
            <option value="">Select a Shipping Method Type</option>
            <option value="opt1">Fixed</option>
            <option value="opt2">Weight and Location Based</option>
        </select>
        <select data-purpose="ShippingMethodCountry">
            <option value="">Select a Location</option>
            <option value="opt1">Country 1</option>
            <option value="opt2">Country 2</option>
            <option value="opt3">Country 3</option>
        </select>
        <select data-purpose="ShippingMethodRegion">
            <option value="">Select a Region</option>
            <option value="opt1">Region 1</option>
            <option value="opt2">Region 2</option>
            <option value="opt3">Region 3</option>
        </select>
    </fieldset>

    <fieldset data-purpose="ShippingMethodWeightRange">
        <input data-purpose="LowerWeight" type="number">
        <select data-purpose="WeightRangeType" data-action="ChangeWeightRangeType">
            <option value="andup">and up</option>
            <option value="to" selected="selected">to</option>
        </select>
        <input data-purpose="UpperWeight" type="number">
        <input data-purpose="WeightRangePrice" type="number">
        <button type="button" data-action="RemoveThis">Remove</button>
    </fieldset>

</form>

The button[data-action='SubmitForm'] has a function bound to it that uses a JQuery each() function to cycle through all selects and inputs in the form and adds them to two objects - DynamicFormValidationRules for passing to JQuery Validation and DynamicFormAjaxData for the AJAX form post.

DynamicFormValidationRules = {
    "Fieldset1_ShippingMethodDetails_ShippingMethodName": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodType": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodCountry": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodRegion": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    }
}

DynamicFormAjaxData = {
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodCountry: ""
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodName: "Express Shipping"
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodRegion: ""
ShippingMethodDetails1_Fieldset1_ShippingMethodDetails_ShippingMethodType: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_LowerWeight: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_UpperWeight: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_WeightRangePrice: ""
ShippingMethodWeightRange2_Fieldset2_ShippingMethodWeightRange_WeightRangeType: "to"
}

After all these values are marshalled in to the object, I call the validate function:

$("#DynamicForm").validate({
    rules: DynamicFormValidationRules,
    submitHandler : ValidateDynamicFormHandler,
});

It validates as expected the first time.

However, when I add ANOTHER shipping method to the form, and call the functions again, the new fields are not picked up and are marked as valid, even though they aren't:

DynamicFormValidationRules = {
    "Fieldset1_ShippingMethodDetails_ShippingMethodName": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodType": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodCountry": {
        "required": true
    },
    "Fieldset1_ShippingMethodDetails_ShippingMethodRegion": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset2_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_LowerWeight": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_WeightRangeType": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_UpperWeight": {
        "required": true
    },
    "Fieldset3_ShippingMethodWeightRange_WeightRangePrice": {
        "required": true
    }
}

Here is the relevant JavaScript:

function FormSubmit(event) {
    AssignFieldIDs()
}

function AssignFieldIDs() {

    console.log("AssignFieldIDs()");

    var myReturn = {};

    var NumFieldsets = $("#DynamicForm").find("fieldset").length;

    $("#DynamicForm").find("fieldset").each(function(index, element){

        var myFieldset = element;
        var myFieldsetIndex = index;
        var myFieldsetNumber = myFieldsetIndex + 1;
        var myFieldsetPurpose = $(element).attr("data-purpose");
        var myFieldsetName;

        if (NumFieldsets > 1) {
            myFieldsetName = myFieldsetPurpose + myFieldsetNumber
        } else {
            myFieldsetName = myFieldsetPurpose;
        }

        console.log(element);

        $(myFieldset).attr("id", "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose);

        $(myFieldset).find("input, select, textarea").each(function(index,element){

            myField = element
            myFieldIndex = index;
            myFieldNumber = index + 1;
            myFieldPurpose = $(element).attr("data-purpose");
            myFieldName = "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose + "_" + myFieldPurpose; //+ myFieldsetNumber;

            // $(element).attr("name", myFieldsetName + "_" + myFieldName);
            $(element).attr("name", myFieldName);
            $(element).attr("id", myFieldName);

            DynamicFormAjaxData[myFieldsetName + "_" + myFieldName] = $(myField).val();
            DynamicFormValidationRules[myFieldName] = {required : true};

        }); 

    });

    PrepareFormValues();

}

function PrepareFormValues(event) {

    console.log("PrepareFormValues()")

    console.log("DynamicFormAjaxData")
    console.log(DynamicFormAjaxData)

    console.log("DynamicFormValidationRules");
    console.log(DynamicFormValidationRules);

    $("#DynamicForm").validate({
        rules: DynamicFormValidationRules,
        submitHandler : ValidateDynamicFormHandler,
    });

    console.log('$("#DynamicForm").valid()');
    console.log($("#DynamicForm").valid());

    if ($("#DynamicForm").valid() === true ) {
        $("#DynamicForm").submit();
    }
    else
    if ($("#DynamicForm").valid() === false ) {

    }


}

Thanks for reading!

Many thanks to @SSA for leading me to the answer.

Instead of appending all the rules using a JQuery function to an object and passing that, I added the rule for each field separately using JQueryValidate's rules() method.

function AssignFieldIDs() {

    console.log("AssignFieldIDs()");

    var NumFieldsets = $("#DynamicForm").find("fieldset").length;

    // Form is validated here, without rules
    $("#DynamicForm").validate({
        submitHandler : ValidateDynamicFormHandler,
    });

    $("#DynamicForm").find("fieldset").each(function(index, element){

        var myFieldset = element;
        var myFieldsetIndex = index;
        var myFieldsetNumber = myFieldsetIndex + 1;
        var myFieldsetPurpose = $(element).attr("data-purpose");
        var myFieldsetName;

        if (NumFieldsets > 1) {
            myFieldsetName = myFieldsetPurpose + myFieldsetNumber;
        } else {
            myFieldsetName = myFieldsetPurpose;
        }

        console.log(element);

        $(myFieldset).attr("id", "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose);

        $(myFieldset).find("input, select, textarea").each(function(index,element){

            // Creates temporary vars for field naming in the objects.
            myField = element;
            myFieldIndex = index;
            myFieldNumber = index + 1;
            myFieldPurpose = $(element).attr("data-purpose");
            myFieldName = "Fieldset" + myFieldsetNumber + "_" + myFieldsetPurpose + "_" + myFieldPurpose; //+ myFieldsetNumber;

            // Sets names and ids in the HTML for use by the 
            $(element).attr("name", myFieldName);
            $(element).attr("id", myFieldName);

            // Validates each field.
            $(element).rules("add", {required:true});

            // Adds to an object for making an AJAX post.
            DynamicFormAjaxData[myFieldsetName + "_" + myFieldName] = $(myField).val();


        }); 

    });

    PrepareFormValues();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM