HTML 5需要Checkbox [英] HTML 5 make Checkbox required

查看:116
本文介绍了HTML 5需要Checkbox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单上有多个复选框。我需要让用户选择至少一个复选框,否则表单将不会提交。我尝试了必需的属性,但它检查用户是否检查了所有复选框。

I have multiple checkbox on my form. I need to make user to select atleast one checkbox or else the form will not submit. I tried required attribute but it checks if user has checked all check boxes.

如何做到这一点?

推荐答案

一种解决方案是向所有复选框添加必需的属性,并且当选中其中至少一个复选框时,使用jQuery删除所有复选框的必需属性。

One solution is to add required attributes to all the checkboxes, and when at least one of these checkboxes is checked, remove the required attributes for all the checkboxes using jQuery.

var requiredCheckboxes = $(':checkbox[required]');

requiredCheckboxes.change(function(){
    if(requiredCheckboxes.is(':checked')) {
        requiredCheckboxes.removeAttr('required');
    }
    else {
        requiredCheckboxes.attr('required', 'required');
    }
});

DEMO

这篇关于HTML 5需要Checkbox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆