mercredi 25 mars 2015

Using jQuery to toggle visibility of various divs based on two sets of checkboxes?


I have a large number of divs/articles that contain contact info for a bunch of wilderness guides. I'm trying to toggle the visibility of each div based on two sets of checkboxes - One set for the activity the guide specializes in (fishing, hunting, etc) and one set for the state they're in (Alaska, Colorado, etc).


There's a somewhat similar question here that I've been trying to follow, but I'm something(s).


I've got the "sport" filters working correctly. The "state" filters are not and therefor, they don't work together either.


The end goal is for user to select as many sports and states as they'd like and filter out (hide) the divs that don't match both the sport and states chosen.


Here's the JSFiddle


The quick and dirty HTML:



<div class="sport-wrapper">
<h2>Choose a Sport:</h2>
<ul>
<li><label for="fish"><input type="checkbox" id="fish" name="sport"/>Fly Fishing</label></li>
<li><label for="hunt"><input type="checkbox" id="hunt" name="sport" />Hunting</label></li>
<li><label for="raft"><input type="checkbox" id="raft" name="sport" />Rafting</label></li>
</ul>
</div>
<div class="state-wrapper">
<h2>Choose a State:</h2>
<ul>
<li><label for="AK" class="guide-available"><input type="checkbox" id="AK" name="state"/>Alaska</label></li>
<li><label for="CA" class="guide-available"><input type="checkbox" id="CA" name="state"/>California</label></li>
<li><label for="CO" class="guide-available"><input type="checkbox" id="CO" name="state"/>Colorado</label></li>
</ul>
</div>
<div class="results">
<h2>Available Guides:</h2>
<div data-category="guide ak fish">
<h3>Joe's Alaska Fishing Tours</h3>
</div>
<div data-category="guide ak fish hunt">
<h3>Mike's Alaska Fishing and Hunting Adventures</h3>
</div>
<div data-category="guide co fish raft">
<h3>Jim's Colorado Rafting and Fishing Lodge</h3>
</div>
<div data-category="guide ca raft">
<h3>California Whitewater Rafting</h3>
</div>
</div>


And the current jQuery (that doesn't quite work):



$('.sport-wrapper, .state-wrapper').delegate('input[type=checkbox]', 'change', function () {
var $lis = $('.results > div'),
$checked = $('input:checked');
if ($checked.length) {
var selector = '';
$($checked).each(function (index, element) {
if (selector === '') {
selector += "[data-category~='" + element.id + "']";
} else {
selector += ",[data-category~='" + element.id + "']";
}
});
$lis.hide();
console.log(selector);
$('.results > div').filter(selector).show();
} else {
$lis.show();
}
});




Aucun commentaire:

Enregistrer un commentaire