Question

I am working on setting up a way to select or filter a list using radio groups of "modifiers" or attributes. The lists I'm filtering can be multi-level nested ul-li.

My eventual goal is to have only the intended list items with the correct attribute or text show, the others would be hidden.

In my example, I'm having issues with selecting only what I want. It's selecting the whole nested ul if there is an li that contains the text I'm looking for.

Here's a jsFiddle I made

$('.refine').on('change', 'input[type="radio"]', function() {

    var sortattr = $(this).val();   

    $(".mylist li:contains('" + sortattr + "')").each(function() {
        $(this).addClass('here');
    });
});

<form class="refine" role="form">
    <input type="radio" value="left" name="modifiers" id="reflatleft">Left
    <input type="radio" value="right" name="modifiers" id="reflatright">Right
    <input type="radio" value="unspecified" name="modifiers" id="reflatunspecifed">Unspecified
</form>                         

<ul class="mylist">
    <li>item misc header
      <ul>
        <li>item left</li>
        <li>item right</li>
        <li>item left</li>
        <li>item unspecified</li>
        <li>item somethings else</li>
      </ul>
    </li>
    <li>item left</li>
    <li>item right</li>
    <li>item left</li>
    <li>item unspecified</li>
    <li>item somethings else</li>
</ul>
Was it helpful?

Solution 2

working solution

You just have to check whether there are any child elements in the <li>'s to be highlighted so just adding a if construct would solve the problem

$('.refine').on('change', 'input[type="radio"]', function() {

    var sortattr = $(this).val();   

    $(".mylist li:contains('" + sortattr + "')").each(function() {
        if($(this).children().length == 0){
            $(this).addClass('here');
        }
    });
});

OTHER TIPS

Add default styles to li:

li{
    color: #000;
    font-weight: normal;
}

at first create an array like below

var myArray=new Array();

then

pust your contents like below

myArray.push(item you want to push);

The reason why whole li is getting selected is because of ur selector.

Your current selector is '.mylist li'.

You code iterates to find the requested text, for eg. 'left' and it adds the css to the complete selector.

So instead of adding class to ".mylist li ul li" it adds the class to ".mylist li" hence the whole outer li gets highlighted.

You can use .has to iterate through the nested ul li

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top