2015-04-06 89 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

相關問題