2015-04-06 22 views
0

我有一个复选框列表,像这样:检查其点击第一个复选框

<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> 

我找的行为是如果我选择在这个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 
    } 
}); 

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

+0

只是一个快速的一个:你复选框动态创建? – 2015-04-06 10:11:38

+0

是的,从ajax填充 – janhartmann 2015-04-06 10:17:24

+1

在那种情况下,我已经做了编辑我的答案,使用正确的'.on()'委托使事件保持活跃状态​​(就像你一样)。编辑。 – 2015-04-06 10:21:02

回答

3

jsBin demo

$(".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); 
    } 
}); 
+0

这样做了,我添加了一个'else {$ first.prop(“checked”,true); }'以确保它不能被取消选中。 – janhartmann 2015-04-06 10:37:59

+0

用那个'else'你会犯一个很大的错误:http://jsbin.com/sumubuyiga/3/edit它会先连续地切换$。 – 2015-04-06 10:40:12

+0

啊哈,我明白了......没有注意到! – janhartmann 2015-04-06 10:40:53

1

您应该使用单选按钮,复选框没有。这将完全符合你的要求,而你不需要额外的努力。即使你在试图做的事情上取得成功,用户界面也会出错。

+0

大声笑,我现在得到了,这就是为什么它downvote其他答案! :)太棒了!寻求适当的指导。但它需要对问题本身产生负面影响! – Vikrant 2015-04-06 10:14:53

+2

它应该能够检查多个复选框:-) – janhartmann 2015-04-06 10:16:45

相关问题