jquery validate check at least one checkbox

前端 未结 9 1930
情书的邮戳
情书的邮戳 2020-12-02 08:32

I have something like this:

相关标签:
9条回答
  • 2020-12-02 09:26

    Mmm first your id attributes must be unique, your code is likely to be

    <form>
    <input class='roles' name='roles' type='checkbox' value='1' />
    <input class='roles' name='roles' type='checkbox' value='2' />
    <input class='roles' name='roles' type='checkbox' value='3' />
    <input class='roles' name='roles' type='checkbox' value='4' />
    <input class='roles' name='roles' type='checkbox' value='5' />
    <input type='submit' value='submit' />
    </form>
    

    For your problem :

    if($('.roles:checkbox:checked').length == 0)
      // no checkbox checked, do something...
    else
      // at least one checkbox checked...
    

    BUT, remember that a JavaScript form validation is only indicative, all validations MUST be done server-side.

    0 讨论(0)
  • 2020-12-02 09:29
    $("#idform").validate({
        rules: {            
            'roles': {
                required: true,
            },
        },
        messages: {            
            'roles': {
                required: "One Option please",
            },
        }
    });
    
    0 讨论(0)
  • 2020-12-02 09:30

    It's highly probable that you want to have a text next to the checkbox. In that case, you can put the checkbox inside a label like I do below:

    <label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="72" aria-required="true" class="error"> All Over</label>
    <label style="width: 150px;"><input type="checkbox" name="damageTypeItems" value="73" aria-required="true" class="error"> All Over X2</label>
    

    The problem is that when the error message is displayed, it's going to be inserted after the checkbox but before the text, making it unreadable. In order to fix that, I changed the error placement function:

    if (element.is(":checkbox")) {
        error.insertAfter(element.parent().parent());
    }
    else {
        error.insertAfter(element);
    }
    

    It depends on your layout but what I did is to have a special error placement for checkbox controls. I get the parent of the checkbox, which is a label, and then I get the parent of it, which is a div in my case. This way, the error is placed below the list of checkbox controls.

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