jQuery Validation Plugin - make checkbox group required based on dropdown response

前端 未结 1 1656
自闭症患者
自闭症患者 2021-01-25 09:53

I\'m using the jQuery Validation plugin with an HTML form for the first time. I\'m used to using plain old javascript for this, but I totally love this plugin! Anyway, I\'m stuc

相关标签:
1条回答
  • 2021-01-25 10:23

    There are a few ways to do this, and you're on track for one of them. I'm going to suggest a different way though. First off, it makes sense to reorganize your checkboxes to all have the same name attribute but different value attributes. That will make them behave better within jQuery Validate. This is what you have now:

    <input id="Q8yesA" class="Q8yes" name="Q8yesA" type="checkbox" value="Yes" />
    

    Change that to:

    <input id="Q8yesA" class="Q8yes" name="Q8yes" type="checkbox" value="Q8yesA" />
    

    Now, for the actual jQuery Validate code. You probably don't need groups if you do this the way I suggested, instead you can just have rules that look like this:

    rules: {
        Q8: "required",
        Q8yes: {
            required: '#Q8 option[value="Yes"]:selected'
        },
        Q8yesDlist: {
            required: '#Q8yesD:checked'
        }
     }
    

    I've used the dependency-expression version of the required rule.

    Here's what it looks like in action: http://jsfiddle.net/ryleyb/fccPf/

    0 讨论(0)
提交回复
热议问题