繁体   English   中英

选中复选框是否已选中任何复选框

[英]Check checkbox if any of the checkboxes is checked

的HTML

<label for="desktop_dimension_id">Desktop dimensions:</label>
    <span class="checkbox" id="desktopCheckboxId">
    <span class="checkbox_value">
<input id="dc1280_800" type="checkbox" name="1280x800"> 1280x800</span>                    
<span class="checkbox_value">
<input id="dc1366_768" type="checkbox" name="1366x768"> 1366x768</span>
<span class="checkbox_value">
<input id="dc1920_1080" type="checkbox" name="1920x1080"> 1920x1080</span>
</span>

    <br/>                    
 <input id="desktopCheckbox" type="checkbox" name="type[]" value="1"> Desktop

JAVASCRIPT

if(jQuery('#desktopCheckboxId input[type=checkbox]:checked').length) {
        document.getElementById('desktopCheckbox').checked = this.checked;
    }

我要检查桌面复选框是否选中了前三个复选框中的任何一个。 已经尝试了几种方法,但由于未知原因似乎无法正常工作。 那我该怎么做呢?

jsFiddle

http://jsfiddle.net/pmZ7T/

试试这个。

$("#frmTest input[type='checkbox']").each(function(){
    if($(this).is(':checked'))
    {
        $("#desktopCheckbox").attr("checked","checked");
        return true;
    }
});

您可以像下面这样:

$('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);

但是您可能要绑定变更事件。

$('#frmTest input[type=checkbox]').change(function() {
  $('#desktopCheckbox').prop('checked', $('#frmTest input[type=checkbox]:checked').length > 0);
}).change();

参见演示。

怎么样: 演示 http://jsfiddle.net/GGEFp/ * <==将返回false

http://jsfiddle.net/D23eA/ <==将返回true

API: length http://api.jquery.com/length/

休息应该适合需要:)

var atLeastOne = $('#desktopCheckboxId :checkbox:checked').length > 0;

小提琴演示

var chk = $('.checkbox_value input[type=checkbox]');
chk.change(function () {
    $('#desktopCheckbox').prop('checked', chk.filter(':checked').length > 0);
});


参考文献

。更改()

。支柱()

。过滤()

您可以将checked = true设置为...

if (jQuery('input[type=checkbox]:checked').length) {
        document.getElementById('desktopCheckbox').checked = true;
    }

http://jsfiddle.net/pmZ7T/4/

(顺便说一句,您的小提琴也在寻找不存在的表单ID ...“ frmTest”)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM