Bogdan
Bogdan

Reputation: 1911

jQuery: how can I select only the checkboxes that are visible and checked?

I'm trying to check whether or not all the visible check boxes in a certain series are checked and i thought of just counting those that are visible and those that are visible and checked to see if the numbers are the same. The problem is I can't get the visible nor the checked selectors to work.

These are some of the ideas I had but didn't work:

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

both sides are 0 in this case

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

also returned 0 on both sides.

Also tried

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

and this also returns 0 on both sides.

As a note $j("input[id^='chk_camp']").length returns the correct value. Also the browser I'm working with is Firefox.

What am I doing wrong here?

Answer: Aparently what I'm doing wrong is somewhere else. I was doing these checks before actually making the div containing the checkboxes visible so all the visibility checks were returning false.

Upvotes: 12

Views: 17700

Answers (3)

This works fine for me.

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

OR adapting the above answer.

jsfiddle

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

Upvotes: 10

Joonas
Joonas

Reputation: 7303

You could do something like this:

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

Upvotes: 10

palaѕн
palaѕн

Reputation: 73906

This is incorrect:

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

Upvotes: 2

Related Questions