开发者

JQuery: Validation On The Fly

I have a script which calls a php file and开发者_开发技巧 gets the proper fields to show each time a select box (category) is changed. Along with each row, there is a value (0 or 1) to show if that field is required or not. If you look below, the each() function on data shows "key" being the row, and "val" being whether it's required or not.

I currently check to see if it's required, and then push the "key" into an array.Now, the tricky part, I want to modify the validate function to include all of the elements in the array "req" (essentially building the validation requirements on the fly). Currently, only "category" is required (it needs to be added to the "rules" section of validate)

$('#category').change(function() {
    var cid = $(this).val();

    $.get('./ajax/get_cat_info.php?cid=' +cid, function(data, textStatus) {

        var req = new Array();

        $.each(data, function(key, val) {

            $('#' + key).show();
            if(val == 1) {
                req.push(key);
            }
         });
    }, 'json');

    // Validation:
    $("#submissionForm").validate({
        rules: {
            category: "required"
        },
        messages: {
            category: ""
        }
    }); 
});


Would something like this help?

$('#category').change(function() {
    var cid = $(this).val();
    var myRules = cid.data('rules') || {};

    $.get('./ajax/get_cat_info.php?cid=' +cid, function(data, textStatus) {
        $.each(data, function(key, val) {
            $('#' + key).show();
            if(1 == val) {
                myRules[key]="required";
                cid.data('rules',myRules);
            }
         });
    }, 'json');

    // Validation:
    $("#submissionForm").validate({
        rules    : $.extend({category: "required"},cid.data('rules')),
        messages : {
            category: ""
        }
    }); 
});

http://api.jquery.com/jQuery.extend/

http://api.jquery.com/data

Would this method of storing it locally provide a mechanism that would help?

Thanks, MyStream

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜