使用JavaScript验证checkbox checked属性是否为空



我想验证checkboxes checked属性。如果其中任何一个没有被选中,在span中显示这句话:"你应该选择其中一个",当我选择其中一个时,消息必须消失。

<form  method="get"action="#" onsubmit="return vali();">
    <span id="textspan" style="color:red"></span>
    <input type="checkbox" class='gender' id="male">male
    <input type="checkbox" class='gender' id="female">female
    <input type="submit" class="validate" value="send" />
</form>
function vali() {
    var bool = true;
    var checkedCount = $('input[class="gender"]:checked').length;
    if (checkedCount == 0) {
        $("#textspan").html('select one of them');
        bool = false;
    }
    if(checkedCount >= 1) 
    {
        $("#textspan").html('');
        bool = true;
    }
    return bool;    
}

您没有为复选框的更改(或单击)事件添加任何功能:

您的函数'vali()'附加到表单提交这意味着你的功能将只工作,如果你点击发送按钮

所以如果你有你的错误,你想没有它当你点击其中一个(复选框),你必须添加一个函数到该事件:

function vali() {
    var bool = true;
    var checkedCount = $('input[class="gender"]:checked').length;
    if (checkedCount == 0) {
        $("#textspan").html('select one of them');
         bool = false;
    }
    if(checkedCount >= 1) 
    {
        $("#textspan").html('');
        bool = true;
    }
    return bool;
}
$(".gender").click(function(){
    var checkedCount = $('input[class="gender"]:checked').length;
    if(checkedCount >= 1){
                $("#textspan").html('');
            }
});

,当您单击您的'。"性别",最好将您的功能设置为:

$(".gender").click(function(){
    $("#textspan").html('');
});

try below

<form  method="get"action="#" onsubmit="return vali();">
    <span id="textspan" style="color:red"></span>
    <input type="radio" name="rad" class='gender' id="male">male
    <input type="radio" name="rad" class='gender' id="female">female
    <input type="submit" class="validate" value="send" />
    </form>
<script>        
        $(document).ready(function(){
        $(".gender").click(function(){
        $("#textspan").html('');
    });
    });
         function vali() {
            var bool = true;
                var checkedCount = $('input[class="gender"]:checked').length;
                if (checkedCount == 0) {
                    $("#textspan").html('select one of them');
                    bool = false;
                }
                if(checkedCount >= 1) 
                {
                    $("#textspan").html('');
                    bool = true;
                }
                return bool;
        }
        </script>

提琴手喜欢:-这里

最新更新