Skip to content Skip to sidebar Skip to footer

JQuery Checkbox Filter, Working But Want To Reset When Unchecked

I'm building a filter for a selection of condos. I've figured out how to filter using a slider and now also need to filter by number of bedrooms using two checkboxes.

Solution 1:

You are marking elements that have the data tag bdrms set to 1 as invisible. This does not change. So once they are invisible, they will remain that way.

There are several ways to solve this, one being a seperate function that's being called when the checkbox isn't checked:

if($(this).is(':checked')){
    filterItems();
} else {
    resetAll();
}

After that it's a simple matter of writing a function that resets the invisble elements back to visible:

function resetAll()
{
    $.each($('.condo-box'), function() {
        $this = $(this);
        if($this.is(":hidden")){
            $this.show();
        }
    });
}

So updating your fiddle would be: https://jsfiddle.net/3y9vz1q1/1/ Which works fine.

UPDATE:

A far better solution would be to make both checkboxes work and use a single function:

$(document).ready(function() {
    $("#1bdrm, #2bdrm").click(function() {
    var bdrm1 = false;
    var bdrm2 = false;
    if($("#1bdrm").is(':checked')){
        bdrm1 = true;
    }
    if($("#2bdrm").is(':checked')){
        bdrm2 = true;
    }

    filterItems(bdrm1, bdrm2);
  });
});

function filterItems(bdrm1, bdrm2){
    $.each($('.condo-box'), function() {
    $this = $(this);
    itemData = $this.data();
    if(bdrm1 && !bdrm2){
      if(itemData.bdrms == 1){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    }
    else if(bdrm2 && !bdrm1){
      if(itemData.bdrms == 2){
        $this.show();
        itemData.matching = true;
      } else {
        $this.hide();
        itemData.matching = false;
      }
    } else {
        $this.show();
        itemData.matching = true;
    }
  });
}

Fiddle update: https://jsfiddle.net/3y9vz1q1/2/


Solution 2:

Always, when you click to checkbox, filter funtion started and because last item

$('#lawrence').data({
  id: 10,
  sqft: 467,
  bdrms: 1
});

has 1, list don't reset

Try it:

  $(document).ready(function() {
        var theValue;

        $("#1bdrm").click(function() {
          if(this.checked){
            filterItems(false);
              }else{
            filterItems(true);
            }
        });
      });

      function filterItems(reset)
      {
        $.each($('.condo-box'), function() {
          $this = $(this);
          itemData = $this.data();
          if(itemData.bdrms == 1 || reset === true){
            $this.show();
            itemData.matching = true;
          } else {
            $this.hide();
            itemData.matching = false;
          }
        });
      }

Post a Comment for "JQuery Checkbox Filter, Working But Want To Reset When Unchecked"