检查它的第一个复选框是否被点击

jan*_*ann 0 javascript checkbox jquery

我有一个复选框列表,如下所示:

<div class="checkbox-list">
     <label><input type="checkbox" value="" /> All items</label><br />
     <label><input type="checkbox" value="1" /> First item</label><br />
     <label><input type="checkbox" value="2" /> Second item</label><br />
     <label><input type="checkbox" value="3" /> Third item</label><br />
     <label><input type="checkbox" value="4" /> Forth Checkbox</label>
</div>
Run Code Online (Sandbox Code Playgroud)

我正在寻找的行为是,如果我在选中此div( .checkbox-list input[type=checkbox]:first) 所有其他复选框后选中第一个复选框。同样,如果我选择第一个以外的任何一个,第一个将被取消选择。

我正在努力如何检查第一个是否被点击?

$(".checkbox-list").on("change", "input[type=checkbox]", function () {
    if ($(this).first()) { // <- not working - how do I know if I clicked the first one?
        $("input[type=checkbox]:checked", ".checkbox-list").not(this).prop("checked", false);
        $(this).prop("checked", true);
    } else {
         // Uncheck first checkbox
    }
});
Run Code Online (Sandbox Code Playgroud)

如果你想玩,这里有一个小提琴:http : //jsfiddle.net/4c7aubqL/1/

Rok*_*jan 5

jsBin 演示

$(".checkbox-list").on("change", ":checkbox", function() {
    var $all   = $(".checkbox-list").find(":checkbox");
    var $first = $all.eq(0);
    if ($first.is(":checked")) { 
        $all.not(this).prop("checked", false);
    }
});
Run Code Online (Sandbox Code Playgroud)