2013-05-20 59 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 />'); 
}); 
相关问题