Reputation: 665
I have the following div which contains a select list of tags (categories) which, when selected filter (hide) any li containing the word selected. This works well, however I would actually like it to hide the parent .
For example if Neurology was selected, I would want to have Heading 2 and its parent ul still visible along with Neurology. If Diabetes is selected, I would want the parent ul to be hidden completely.
Can anyone help with this?
HTML
<div id="container">
<select id="tags">
<option>Cancer</option>
<option>Diabetes</option>
<option>Obesity</option>
</select>
<ul class="itemdetails">
<li class="heading">Heading 1</li>
<li><a href><span class="tagdetails">Diabetes</span></a></li>
</ul>
<ul class="itemdetails">
<li class="heading">Heading 2</li>
<li><a href><span class="tagdetails">Obesity</span></a></li>
<li><a href><span class="tagdetails">Neurology</span></a></li>
</ul>
</div>
Jquery
var itemlist = $('#container');
$('#tags').change( function () {
var tagsfilter = $(this).val();
if (tagsfilter) {
$matches = $(itemlist).find('span.tagdetails:Contains(' + tagsfilter + ')').parent();
$('a', itemlist).not($matches).hide();
$matches.show();
} else {
$(itemlist).find("a").show();
}
return false;
})
Upvotes: 0
Views: 90
Reputation: 287
updated code.
1) $('.tagdetails:not(:contains("'+tagsfilter +'"))').closest('li').hide();
First we select and hide all the li
elements which does not contain value text of the selected option.
2) $('.itemdetails:not(:has(li:visible>a>span))').not('.heading').hide();
Next we select all the ul
elements with class itemdetails which has visible li
child element which in turn has descendants a
and span
and does not have a heading class and hide it.
$('#tags').change( function () {
$('.itemdetails').show();
$('.tagdetails').closest('li').show();
var tagsfilter = $(this).val();
if($('.tagdetails:contains("'+tagsfilter+'")').length > 0){
$('.tagdetails:not(:contains("'+tagsfilter +'"))').closest('li').hide();
$('.itemdetails:not(:has(li:visible>a>span))').not('.heading').hide();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<select id="tags">
<option>Cancer</option>
<option>Diabetes</option>
<option>Obesity</option>
<option>Others</option>
</select>
<ul class="itemdetails">
<li class="heading">Heading 1</li>
<li><a href><span class="tagdetails">Diabetes</span></a></li>
</ul>
<ul class="itemdetails">
<li class="heading">Heading 2</li>
<li><a href><span class="tagdetails">Obesity</span></a></li>
<li><a href><span class="tagdetails">Neurology</span></a></li>
</ul>
<ul class="itemdetails">
<li class="heading">Heading 3</li>
<li><a href><span class="tagdetails">Diabetes</span></a></li>
<li><a href><span class="tagdetails">Others</span></a></li>
</ul>
</div>
Upvotes: 1