[Fixed]-Filter Using Checkboxes w. Jquery

1đź‘Ť

Here’s a working one with your example, you’ve had to put the “id” for the sections, or in other case, change the jquery selector for it’s class.

Also you have to set the click action for the input checkbox elements.

Hope this helps.

//initialize state
$("#mlb").hide();
$("#nfl").hide();


$("input[type=checkbox]").on('click', function() {
  var thisval =  $(this).val();
  if ($(this).prop('checked')){
      $('#' + thisval).show();
    }
  else{
    $('#' + thisval).hide();
    }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sport-filter" class="mlb">
     <label for="mlb-filter"><input type="checkbox" value="mlb" id="mlb-filter">mlb</label>
</div>
 <div id="sport-filter" class="nfl">
     <label for="nfl-filter"><input type="checkbox" value="nfl" id="nfl-filter">nfl</label>
</div>

<section class=mlb id="mlb">
  <p>
    Hey
  </p>
</section>
<section class=nfl id="nfl">
  <p>
    Hey 2
  </p>
</section>
👤Jordi Flores

0đź‘Ť

Here’s an example of how .each works in jquery

function toggleChks() {
$("input[type=checkbox]").each(function(index, item) {
  console.log(index, item);
  if ($(item).prop('checked'))
    $(item).prop('checked', false);
  else
    $(item).prop('checked', true);
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button onclick="toggleChks()">toggle</button>
<input type="checkbox" checked value="1">
<input type="checkbox" checked value="2"> 
<input type="checkbox" checked value="3">
<input type="checkbox" value="4">
<input type="checkbox" value="5">
<input type="checkbox" value="6">
👤Jordi Flores

Leave a comment