开发者

Validate field with jquery only if checkbox is selected

I have several checkboxes with the same name and the last checkbox is basically "Other" with an empty text field next to it. I'm using jque开发者_JS百科ry validation and I want to make the empty text field required when the checkbox for other is selected.

Not sure how to do this with the checboxes all having the same name.

Thanks.


The checkboxes have the same name, but different values. So you can find the selected and then check the values for a particular one. I did something similar with radio buttons. Here's one of my rules that says the daypattern field is required if the recurpattern radiobutton has a value of 'day'.

        daypattern: {
            required: 
                function(element){
                    return ($("input[name='recurpattern']:checked").val() == 'day')
                }

        }

In your case, your checkbox set has an array in yourcheckboxes.val(). So you check that your test value is in that array.


You can select all these checkboxes and use the :last - selector (http://api.jquery.com/last-selector/) or you select the inputfield and go up through the DOM with $(".myOtherInput").prev() if it is directly in front of your field. After that you can bind the function to add or remove class="required".

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜