Select all <li> that have no checkbox

I have a list box <li>

with a checkbox in each of them and I want to hide all <li>

that do not have a checkbox checked.

I currently do this by first hiding everything <li>

and then hiding the ones that have the checkbox checked, like this:

$("#categoryList").find('li').each(function () {
    $(this).addClass("searchhide");
});

$("#categoryList").find("input[type=checkbox][checked]").each(function () {
    $('#id-' + $(this).attr('rel')).removeClass("searchhide");
});

      

But isn't it possible to do this in an easier way, only by hiding the ones that should be hidden in the first place?

 $("#categoryList").find('li').not("input[type=radio][checked]").each(function () {
     $(this).addClass("searchhide");
 });

      

+3


source to share


3 answers


$('#categoryList li > input[type="checkbox"]')
    .not(":checked")
    .parent()
    .addClass("searchhide");

      



+4


source


I would recommend using filter for this purpose;

$('ul li')
    .filter(function() {
        return $(this).find('input:checked').length == 0;
    })
    .addClass('searchhide'); // or .hide()

      

It just selects all items li

and filters the collection only for those that contain an unchecked item input

.



Made this simple jsfiddle to demonstrate the function.

Including relevant HTML;

<ul>
    <li>A <input type="checkbox" checked="checked" /></li>
    <li>B <input type="checkbox" /></li>
    <li>C <input type="checkbox" checked="checked" /></li>
    <li>D <input type="checkbox" /></li>
    <li>E <input type="checkbox" checked="checked" /></li>
    <li>F, li without a checkbox</li>
    <li>G, multiple checkboxes
        <input type="checkbox" checked="checked" />
        <input type="checkbox" />
    </li>
    <li>H <input type="text" value="text field" /></li>
</ul>

      

+1


source


demo : http://jsbin.com/usepob/2/

 $('#categoryList li :checkbox:not(:checked)').parent().addClass("searchhide");

      

0


source







All Articles