Search code examples
javascriptfiltermootools

Mootools Select filtering


I would like to show specific <li> elements when I click on one of the options from such a <select>:

<select>
    <option value="f_chzn_g_0">Group One</option>
    <option value="f_chzn_g_4">Group Two</option>
</select>

This is my <li>'s which would get filtered to show only selected group.

<ul>
    <li id="f_chzn_g_0" class="group-result">Group One</li>
    <li id="f_chzn_o_1" class="active-result group-option" style="">one</li>
    <li id="f_chzn_o_2" class="active-result group-option" style="">two</li>
    <li id="f_chzn_o_3" class="active-result group-option" style="">three</li>
    <li id="f_chzn_g_4" class="group-result">Group Two</li>
    <li id="f_chzn_o_5" class="active-result group-option" style="">one</li>
    <li id="f_chzn_o_6" class="active-result group-option" style="">two</li>
    <li id="f_chzn_o_7" class="active-result group-option" style="">three</li>
</ul>

Can someone help me out with this? It all has to be in Mootools. Thanks!


Solution

  • You just need a state variable that tracks whether you're in the selected group when iterating over the li elements. Assuming that you show li elements by adding the active-result class, something like the following should work:

    function showSelectedListItems(ulElem, selectedId) {
        var inSelectedGroup = false;
    
        ulElem.getElements('li').each(function(liElem) {
            if (!inSelectedGroup) {
                if (liElem.id == selectedId) inSelectedGroup = true;
            }
            else {
                if (liElem.hasClass('group-result') inSelectedGroup = false;
                else liElem.addClass('active-result');
            }
        });
    });