Using depends with the jQuery Validation plugin

前端 未结 8 512
[愿得一人]
[愿得一人] 2021-01-12 11:52

I\'ve got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.

When enabled, the values in these textbo

8条回答
  •  暖寄归人
    2021-01-12 12:41

    Usually when doing this, I skip 'depends' and just use the required jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a quick demo of how I accomplish this, using your markup.

    Really, it boils down to required:'#OneSelected:checked'. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a .valid() call in the checkbox click handler if you want the entire form to validate upon click.

    (Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to textBox is just as effective.)

提交回复
热议问题