2013-05-20 53 views
4

我想檢查是否所有可見的複選框在某個系列中都被選中,我想只計算那些可見的和那些可見的,並檢查數字是否相同。問題是我無法看到可見和檢查選擇器的工作。jQuery:我怎樣才能選擇可見和檢查的複選框?

這些都是一些想法我有,但是沒有奏效:

if($j("input[id^='chk_camp']:visible:checked").length == $j("input[id^='chk_camp']:visible").length) 

雙方0在這種情況下

if($j("input[id^='chk_camp']").filter(':visible').filter(':checked').length == $j("input[id^='chk_camp']").filter(':visible').length) 

也是雙方返回0。

也試過

if($j("input[id^='chk_camp'][visible][checked]").length == $j("input[id^='chk_camp'][visible]").length) 

,這也是雙方返回0。

作爲備註$j("input[id^='chk_camp']").length返回正確的值。我正在使用的瀏覽器是Firefox。

我在這裏做錯了什麼?

答:自然,我做錯了什麼是別的地方。在實際使包含複選框的div可見之前,我正在執行這些檢查,因此所有可見性檢查都返回false。

+1

代碼工作正常的我。看看這個[FIDDLE](http://jsfiddle.net/mojtaba/yerpm/1/)。也許你在其他地方犯了一個錯誤。 – 2013-05-20 09:07:30

+0

@NOX是的,我確實做錯了什麼。我做了檢查之前,我使容器div可見,所以他們顯然返回錯誤的可見檢查。 – Bogdan

回答

4

你可以做這樣的事情:

jsfiddle

的jQuery:

$('input').each(function() { 

    // If input is visible and checked... 
    if ($(this).is(':visible') && $(this).prop('checked')) { 

     $(this).wrap('<div />'); 

    } 

}); 

HTML:

<input type="checkbox" checked="checked"> 
<input type="checkbox" checked="checked" style="display: none;"> 
<input type="checkbox"> 
<input type="checkbox" checked="checked" style="display: none;"> 
<input type="checkbox" checked="checked"> 
<input type="checkbox"> 

CSS:

div { float: left; background: green; } 
div input { display: block !important; } 
+0

我會將此標記爲答案,因爲這對於選擇器實際上不起作用的很好的解決方案。即使我的特殊問題在其他地方,如果選擇者實際上是錯誤的,你的答案也是有效的。 – Bogdan

2

這是不正確的:

if($j("input[id^='chk_camp']").filter(':visible').filter(':checked).length == $j("input[id^='chk_camp']).filter(':visible').length) 
//               ------^------ missing qoutes here  ----^--- also double quotes here 
+0

misstype,對不起。感謝您的支持,我馬上修復它。 – Bogdan

+1

@Bogdan:代碼似乎在工作[** Fiddle **](http://jsfiddle.net/hN28E/)。確保複選框ID是正確的。 –

+0

呃這很尷尬。他們確實有效,問題是在我真正將容器div顯示出來之前,我正在進行所有檢查,因此當然他們全部返回0,因爲當時沒有可見的容器... – Bogdan

6

這工作對我很好。

$(".inputClass:checked:visible"); 
$(".inputClass:checked:visible").length; 

或修改上述答案。

jsfiddle

$('input:visible:checked').each(function() { 
    $(this).wrap('<div />'); 
}); 
相關問題