2

I'm trying to filter some divs with checkboxes using the following code:

$("#filterControls :checkbox").click(function() {
  $(".sectionContent").hide();
  $("#filterControls :checkbox:checked").each(function() {
    $("." + $(this).val()).show();
  });
  if($("#filterControls :checkbox").prop('checked') == false){
    $(".sectionContent").show();
  }
});

This works fine when you check the first checkbox, but it only filters with the others when you also have the first checkbox selected. It's hard to explain but try the JSFiddle: http://jsfiddle.net/BY9JL/

I don't want it to rely on having the first checkbox checked, is there a way around this?

2 Answers 2

5

Try

var sections = $('.sectionContent');
function updateContentVisibility(){
    var checked = $("#filterControls :checkbox:checked");
    if(checked.length){
        sections.hide();
        checked.each(function(){
            $("." + $(this).val()).show();
        });
    } else {
        sections.show();
    }
}

$("#filterControls :checkbox").click(updateContentVisibility);
updateContentVisibility();

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

2 Comments

@Godge check the attached demo
Thanks, I still want it to show all the divs if no checkboxes are checked though.
3

It's because your last if check, it will only check the first checkbox if it is checked or not.

You could change your last if block to see if there are any checked at all:

if($("#filterControls :checkbox:checked").length == 0){
    $(".sectionContent").show();
}

2 Comments

Ahh.. beat me to it, +1 :)
I should've explained this a bit better: if none of the checkboxes are checked, I want all the divs to reappear. Your code fixed my initial problem but stopped them all from reappearing if the checkboxes are unchecked again. Any ideas?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.