views:

290

answers:

2

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 jquery 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.

A: 

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".

toniL
how do i piggy back :last and :checked together? I found this (http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-expression) and here is my code but its not working:$("#4_observerstxt").rules("add", { required: "#4_observers:last:checked"});$("#4_observers:last").click(function() { $("#4_observerstxt").valid();});
jethomas
+2  A: 

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.

dnagirl