How do validate a group of radio buttons?

前端 未结 1 2047
感情败类
感情败类 2021-01-28 00:01

I have a online survey and I am using jquery validation on it.

So each question has 4 options, where each option is a radio button.

When I am building my jquery

相关标签:
1条回答
  • 2021-01-28 00:35

    You're improperly closing your rules with a });...

    rules : {     
        someQuestionId123 : {required : true }
    });
    

    Using the jQuery Validate plugin's .validate() method, you must reference them by name.

    Since a group of radio buttons should all share the same name, you're already doing it properly (after fixing an issue with your brackets)...

    $(document).ready(function() {
    
        $("#myForm").validate({
            rules: {     
                someQuestionId123: { // <-- NAME attribute
                    required: true 
                }
            }  // <-- right here, you incorrectly had '});'
        });
    });
    

    HTML:

    <input type="radio" name="someQuestionId123" value="one" />
    <input type="radio" name="someQuestionId123" value="two" />
    <input type="radio" name="someQuestionId123" value="three" />
    <input type="radio" name="someQuestionId123" value="four" />
    

    DEMO: http://jsfiddle.net/5dsJQ/


    And finally, your latest jsFiddle is broken because you have special characters, such as -, inside your name...

    rules: {     
        someQuestionId-123: { 
            required: true 
        }
    }
    

    As per the "reference docs", you need to enclose the name in quotes to fix this issue...

    rules: {     
        "someQuestionId-123": { 
            required: true 
        }
    }
    

    In general, if you're using these names as JavaScript targets, you'd avoid naming with dashes, -, because JavaScript could sometimes interpret them as minus signs. For jQuery Validate, the quotation marks will get around this problem.

    http://jsfiddle.net/RB4NU/12/

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