开发者

jquery validator - Validating visible elements only

I have a radiobutton that hides/shows a div. All visible elements are "required", but adding ignore: ":hidden" after the validation rules, doesn't work... Here's the code:

<script type="text/javascript">

        $(document).ready(function(){
            $("#myForm").validate({
                rules: {
                    name: "required",
                    age: "required",
                    height: "required",
                    ignore: ":hidden"
                }
            })
        });

    </script>
</head>
<body>
    <form id="myForm" name="myForm" method="post" action="" >
        <input type="radio" name="checkAge" value="adult" onclick="$('#minorRequisites').hide();" />Adult<br/>
        <input type="radio" name="checkAge" value="minor" onclick="$('#minorRequisites').show()" checked="checked"/>Child<br/>
        Name <input id="name" name="name" type="text" /><br/>
        <div id="minorRequisites">
            Age <input id="age" name="age" type="text" /><br/>
            Height <input id="height" name="height" type="text" /><br/>
        </div>
        <input type="submit" />
    </form>
</body>

I want to be able to submit the form givi开发者_如何学Cng only name if "Adult" is checked... Any ideas? :)


You can specify dependency expressions in your required rules to have them ignore the elements if they're not visible:

$("#myForm").validate({
    rules: {
        name: "required",
        age: {
            required: "#age:visible"
        },
        height: {
            required: "#height:visible"
        }
    }
});

You can see the results in this fiddle.

EDIT: ignore will also work, but it's an option, not a rule, so you should write:

$("#myForm").validate({
    ignore: ":hidden",
    rules: {
        name: "required",
        age: "required",
        height: "required"
    }
});


Please try ignore: ":not(:visible)" instead of ignore: ":hidden".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜