views:

140

answers:

2

Hello, I am trying to figure out how to filter in/out content with checkboxes using jquery. Being very new to jquery I have no idea how to approach this the correct way.

I would like three checkboxes like this:

<div class="check_filter">
    <div id="filter">
        <input type="checkbox" id="apple" /><label for="apple">Apple</label>
        <input type="checkbox" id="pear" /><label for="pear">Pear</label>
        <input type="checkbox" id="peach" /><label for="peach">Peach</label>
    </div> 
</div>

Then I would have the content that could be filtered:

<div id="content" >
     <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>  
     <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>  
     <p>Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p>  
     <p>Pellentesque ac sem ac sem tincidunt euismod.</p>  
     <p>Duis hendrerit purus vitae nibh tincidunt bibendum.</p>  
     <p>Nullam in nisi sit amet velit placerat laoreet.</p>  
     <p>Vestibulum posuere ligula non dolor semper vel facilisis orci ultrices.</p>
</div>

I wondering the best way to filter out the data when the checkbox is checked or unchecked.

Thank you for any help on this.

+1  A: 
$('#apple').change(function(){
   var checked = $(this).is(":checked");
   if( checked )
   {
      filterContentForApple();
   }  
});

and then something like...

function filterContentForApple()
{
   $('#content p').each(function(){
      if( $(this).is(":contains('apple')" )//or some other condition
      {
         $(this).hide();
      }
      else{
         $(this).show();
      }
   })
}

Of course, you could always make a filter() function that takes a function predicate as argument, but this should give you a general idea of how to do what you're asking.

Stefan Kendall
I'm not sure what to put where it says "matches some predicate..." above. do I do something with this?
DonDraper01
Whatever type of line filtering you need to do, do it.
Stefan Kendall
+1  A: 

You could put classes on the <p>s you want to hide and then use toggle to show and hide them:

HTML:

<div id="content" >
     <p class="apple">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>  
     <p>Vestibulum consectetur ipsum sit amet urna euismod imperdiet aliquam urna laoreet.</p>  
     <p class="pear">Curabitur a ipsum ut elit porttitor egestas non vitae libero.</p>  
     <p class="apple peach">Pellentesque ac sem ac sem tincidunt euismod.</p>  
     <p>Duis hendrerit purus vitae nibh tincidunt bibendum.</p>  
     <p>Nullam in nisi sit amet velit placerat laoreet.</p>  
     <p>Vestibulum posuere ligula non dolor semper vel facilisis orci ultrices.</p>
</div>

jQuery:

$("#apple").toggle(
      function () {
        $('.apple').hide();
      },
      function () {
        $('.apple').show();
      }
    );
Adam