1
votes

On our website we have a tab with nested filters "Filter 1" is the first level, and Filter 1 has a number of sub-levels, and my task is to let the user choose only one option from all nested select options. So, on click event I add class "selected", lets's say user clicked option with id=2, but if the user clicks option with id=4, I need to remove the class selected from id=2.

If it would be under one branch I could use jquery's sibilings() to check, if any other element has the "selected" class, but how can I do it it the nested dropdown menu to check class "selected" among the children of siblings of the parent?

<details class="block filter">
  <summary>Fitler 1</summary> 
  <ul> 
    <details>
    <ul>
      <summary>Nested level 2.1</summary>
      <ul>
       <li id="1"></li>
       <li id="2"></li>
       <li id="3"></li>
      </ul>
    </ul>
    </details>
    <details>
    <ul>
      <summary>Nested level 2.2</summary>
      <ul>
       <li id="4"></li>
       <li id="5"></li>
       <li id="6"></li>
      </ul>
    </ul>
    </details>
    <details>
    <ul>
      <summary>Nested level 2.3</summary>
      <ul>
       <li id="7"></li>
       <li id="8"></li>
       <li id="9"></li>
      </ul>
    </ul>
    </details>
    ...
  </ul>

</details>
1
if($("ul > li.selected").length) This is to check if any .selected li within any ulMohamed-Yousef

1 Answers

1
votes

Well if they have common classes or names, or even if they are the only select elements:

First, capture the click event (I've used .class-common-on-all-your-selects, but you could use name=[blabla] or even select:

$(document).on('click', '.class-common-on-all-your-selects', function(){
 $('.class-common-on-all-your-selects').prop("selected", false)
 $(this).prop("selected", true)
})

Inside you unselect all elements with the specified class, after that, you mark the clicked option as selected.