I have a nested list of checkboxes which I need to filter them down based on textbox input compared to the label's value. The list looks like this but a lot larger:
Fiddle: https://jsfiddle.net/y9qqgjp5/
However, I'm having trouble with the nested part of this. As I have it now, if you go to search a user (2nd level item), the parent becomes hidden because it doesn't match and thus makes the children hidden, as well. It works fine with filtering on a parent.
Here's the simplified structure I'm filtering on.
HTML:
<input type="text" id="filter" />
<span class="checkbox-list">
<ul>
<li>
<label>Item1</label>
<ul>
<li>
<label>Item2</label>
</li>
<li>
<label>Item3</label>
</li>
<li>
<label>Item4</label>
</li>
<li>
<label>Item5</label>
</li>
</ul>
</li>
<li>
<label>Item6</label>
</li>
<li>
<label>Item7</label>
<ul>
<li>
<label>Item4</label>
</li>
<li>
<label>Item8</label>
</li>
</ul>
</li>
</ul>
</span>
JQuery:
$('#filter').keyup(function() {
var valThis = $(this).val().toLowerCase();
if (valThis == "") {
$('.checkbox-list > ul > li > label').parent().show();
} else {
$('.checkbox-list > ul > li > label').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
if (valThis == "") {
$('.checkbox-list > ul > li > ul > li > label').parent().show();
} else {
$('.checkbox-list > ul > li > > ul > li > label').each(function() {
var text = $(this).text().toLowerCase();
(text.indexOf(valThis) >= 0) ? $(this).parent().show(): $(this).parent().hide();
});
};
});
Any help is appreciated. I can't wrap my head around the nested part of this.
