views:

59

answers:

1

I'm trying to use jQuery validation for a dynamic form I'm setting up.

In some cases this form contains a set of input boxes which are suppose to total 100.

An example might be:

Please indicate what percentage of students are in each grade?
Grade 9: TextBox1
Grade 10: TextBox2
Grade 11: TextBox3
Grade 12: TextBox4

I want to verify that TextBox1 + TextBox2 + TextBox3 + TextBox4 = 100%.

How do I go about this?

Thanks!

+2  A: 
<script>
$(document).ready(function(){
    $("#some-form").validate({

        rules: {
            TextBox1: {
                required: true,
                number: true,
                min: 0,
                max: 100,
            },
            TextBox2 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }
            TextBox3 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }
            TextBox4 : {
                required: true,
                number: true,
                min: 0,
                max: 100,
            }

        },
        submitHandler: function(form){
            var total = parseInt($("#TextBox1").val()) + parseInt($("#TextBox2").val()) + parseInt($("#TextBox3").val()) + parseInt($("#TextBox4").val());
            if (total != 100) {
                $(".error").html("Your total must sum to 100.")
                return false;
            } else form.submit();
        }

    });
});

</script>

Stolen and edited from here.

Marko
Hrm... this is definitely a valid answer (and very complete at that). But not exactly what I'm looking for. The problem is there may be more than 1 group of fields that need to validated. Also the field names are generated at runtime so the javascript would need to be dynanmically written out as well. Either way this is a great starting point! I can probably take it from here but feel free to add some more suggestions if you have any. Thanks!
Justin
No worries @Justin. How about using a simple .sum() method(http://viralpatel.net/blogs/2009/07/sum-html-textbox-values-using-jquery-javascript.html") to calculate textbox arrays? You could use a different class name for each **SET** of textboxes and then if you want, you could even validate on the .keyup() event. I'm not sure what the **rule** would be, but you could post another question with how to validate sets of elements using a class name.
Marko