0

So I want to filter select option dropdown based on what user clicks by id:

document.querySelectorAll('#item-types').forEach(item => {
        item.addEventListener('click', () => {
            const categoriesSelect = document.querySelector('#item-categories')
            const categoriesOptions = Array.from(categoriesSelect.options);
            const selectType = item.dataset.typeId;

            function findMatches(search, categoriesOptions) {
                return categoriesOptions.filter(option => {
                    return option.value.match(search);
                });
            }

            categoriesOptions.forEach(option => {
                option.remove();
                option.selected = false;
            });
            const matchArray = findMatches(selectType, categoriesOptions);
            categoriesSelect.append(...matchArray);
        });
    });
<ul>
   <li id="item-types" data-type-id="1">
       <a href="#">
           <div>Type1</div>
       </a>
   </li>
   <li id="item-types" data-type-id="2">
       <a href="#">
           <div>Type2</div>
       </a>
   </li>
</ul>

<select id="item-categories">
    <option value="1">category1</option>
    <option value="1">category2</option>
    <option value="1">category3</option>
    <option value="2">category4</option>
    <option value="2">category5</option>
</select>

But now when I click any of the list items for the first item it filters out okay, but when I click it second time it returns empty array for options.

zyyyzzz
  • 220
  • 2
  • 11
  • Perrhaps you are looking for the [datalist](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) element? – mplungjan Sep 06 '21 at 07:54
  • Do you want to remove the item from the dropdown which is selected from `
  • ` by matching data-type-id with option value?
  • – navnath Sep 06 '21 at 07:55
  • @NavnathJadhav for example user clicks ```
  • ``` with data-type-id = 1 and then I want to remove ```option values``` where = 2,3,4,5 and leave only ```option value=1```. Now this code works only when I click ```
  • ``` for the first time, but when I click it second time it returns empty ```option``` dropdown
  • – zyyyzzz Sep 06 '21 at 08:00