I.ve been working all night to get this function to work, but i’m too much a noob i think 🙂
I’ve got a list of checkboxes and a list of div’s with corresponding class/id names.
I’d like to have all div’s showed on page load and when a user selects one or multiple checkboxes hide the ones not selected.
Anyone can help me out here??
So far I’ve got the following script :
$('.brand').change(function() {
$('li.merk').not('li#m_' + $(this).attr('id') + '').toggle();
});change();
<input type="checkbox" class="brand" id="Gazelle" />
<input type="checkbox" class="brand" id="Batavus" />
<input type="checkbox" class="brand" id="Trek" />
<input type="checkbox" class="brand" id="KogaMiyata" />
<li class="merk" id="m_Gazelle" style="display:block;">
Gazelle
</li>
<li class="merk" id="m_Batavus" style="display:block;">
Batavus
</li>
<li class="merk" id="m_Trek" style="display:block;">
Trek
</li>
<li class="merk" id="m_KogaMiyata" style="display:block;">
KogaMiyata
</li>
SOLVED : user m90 did the trick for me, my updated code = @ http://jsfiddle.net/PbZRF/27/
$('.brand').on('change',function() {
$checked = $('.brand:checked'); //perform selection only once
if ($checked.length){ //checks if there are checked elements at all
$('.merk').hide(); //hide all
$checked.each(function(){
$('li#m_' + $(this).attr('id') + '').show(); //show only the items with corresponding checkboxes
});
} else { //no checked elements
$('.merk').show(); //show all
}
});
<input type="checkbox" class="brand" id="Gazelle" />
<input type="checkbox" class="brand" id="Batavus" />
<input type="checkbox" class="brand" id="Trek" />
<input type="checkbox" class="brand" id="KogaMiyata" />
<li class="merk" id="m_Gazelle" style="display:block;">
Gazelle
</li>
<li class="merk" id="m_Batavus" style="display:block;">
Batavus
</li>
<li class="merk" id="m_Trek" style="display:block;">
Trek
</li>
<li class="merk" id="m_KogaMiyata" style="display:block;">
KogaMiyata
</li>
You could use the
:checked-pseudoclass to do it a little something like this:See: http://jsfiddle.net/PbZRF/16/
EDIT: Responding to your comment you can just check the
.lengthof the$('.brand:checked')selection and “take measures” in case it returns 0 / is falsy:See: http://jsfiddle.net/PbZRF/27/