Tistklehoff
Tistklehoff

Reputation: 43

creating dynamic groups for validation

I'm quite new in jquery validation and I need your help in an easy subject.

I am validating a dynamic table. This table has a button which add rows. One of the fields is a percentage and I'm validating if the sum of percentages for all rows is 100%. But, I can't attach error messages or any invalidate classes to the percentage field. I read about groups, but I can't manage how can I a 'dynamic' group, because I can't know how many rows are there. The row fields have a name like Percentage[0], Percentage[1] and an id generated by .NET MVC3.

Please, can you give me a hand with this? I'm sure I'm skipping any useful info, somewhere... Can anyone put me in the right way?

Thanks a lot in advance.

Regards.


EDIT:

Sure, I'm sorry. Here is my code:

At this moment, I'm using class validations to get all fields I want, but now, I can't show the errors in a div. I want to show only one error, but validate all percentage fields at once.

    <script type="text/javascript">

$.validator.addMethod("checksum", function (value, element, params) {
    var sum = 0;
    $(params.elements).each(function (i, e) {
        sum = sum + parseInt($(e).val());
    });

    return sum == params.total;
}, $.format("The percentage fields must equal {1} "));

$.validator.addClassRules({ totalize: { checksum: { elements: ".totalize", total: 100}} });

$("#myform").validate({ errorPlacement: function (error, element) { 
    if (element.hasClass("totalize")) {
        error.appendTo("#errors") 
    } else {
        error.insertAfter(element);
    }
});

$(function () {

    var $clone = $('<tr><td><input type="text" value="" name="Person[].Name"></td><td><input type="text" value="" name="Person[].Percentage" class="totalize"></td></tr>');

    $("#AddPerson").on("click", function () {
        $clone.clone().appendTo("#people");
    });
});

</script>

<div class="percentages">

    <table class="">
        <caption>
            Percentages
        </caption>
        <thead>
            <tr>
                <th>
                    Name
                </th>

                <th>
                    <button id="AddPerson" type="button">Add</button>
                </th>
            </tr>
        </thead>
        <tbody id="people">
            <tr>
                <td>
                    <input type="text" value="" name="Person[].Name">
                </td>
                <td>
                    <input type="text" value="" name="Person[].Percentage" class="totalize">
                </td>   
            </tr>
        </tbody>
    </table>

    <div id="errors"> 
    </div>

</div>

Upvotes: 3

Views: 1134

Answers (1)

mitch
mitch

Reputation: 1831

You should use rules if you are dynamically adding inputs to your form. Make sure your call the validate() on your form (you were missing the form tags on your code with id="myForm"). Also, I added some 'improvements'. Check out the jsFiddle. or review the following code:

/*I used an array instead of object literal in order to format your message.  The object literal hasn't working */
$.validator.addMethod("checksum", function (value, element, params) {
    var sum = 0;
    $(params[0]).each(function (i, e) {
        ///specify radix 10 and use || incase the value is empty
        sum += parseInt($(e).val(), 10) || 0;
    });
    return sum == params[1];
}, $.validator.format("The percentage fields must equal {1}"));
var totalize = {
    checksum: [".totalize", 100]
};
$.validator.addClassRules("totalize", totalize);
var valSettings = {
    onkeyup: true,
    errorPlacement: function (error, element) {
        if (element.hasClass("totalize")) {
            error.appendTo("#errors");
        } else {
            error.insertAfter(element);
        }
    },
    submitHandler: function (form) {
        form.submit();
    }
};


$(function () {

    $("#myForm").validate(valSettings);
    var $clone = $('<tr><td><input type="text" value="" name="Person[].Name"></td><td><input type="text" value="" name="Person[].Percentage" class="checksum totalize"></td></tr>');

    $("#AddPerson").on("click", function () {
        $clone.clone()
            .appendTo("#people")
            .find("input[name='Person[].Percentage']")
            .rules("add", totalize);
    });
});

Upvotes: 1

Related Questions