0

I have multiple checkbox / textfield related one to each other, PHP generated, with different IDs and names:

<ul>
    <li>
        <input type="checkbox" name="cb_1" id="cb_1">
        <input type="text" name="txt_1" id="txt_1">
    </li>
    <li>
        <input type="checkbox" name="cb_2" id="cb_2">
        <input type="text" name="txt_2" id="txt_2">
    </li>
    ...
    <li>
        <input type="checkbox" name="cb_N" id="cb_N">
        <input type="text" name="txt_N" id="txt_N">
    </li>
</ul>

When each checkbox is checked, the related textfield should be required

I can do this for one pair, like this:

rules: {
    txt_1: {
      required: "#cb_1:checked"
    }

But how to do for all my N pairs? Is there a simple way or do I have to write validation rules one by one?

4

1 回答 1

1

Write a custom validation rule that looks at the sibling checkbox to see it is checked. Like this

$.validator.addMethod("requiredWithCheckbox", function (value, element) {
    if ($(element).siblings(":checkbox:checked").length) {
        return value != '';
    }
    else {
        return true;
    }
}, "You've checked the checkbox, now fill in the field");

then add this rule to the form fields in whatever way you like, for instance you could do this to add the rule to all text fields

$('input[type=text]').addClass('requiredWithCheckbox');
$("form").validate();
于 2013-04-13T00:45:22.657 回答