Search code examples
javascriptjqueryselectors-api

querySelectorAll - Multiple IDs to hide option in two different dropdown menus


I have two dropdown menus in the same page with two different Ids, and when the option "No" is selected on each one, I'd like them to hide a <div>

I've been trying to make work the function document.querySelectorAll("#Id1, #Id2); but obviously I'm doing something wrong.

This is what I got so far:

document.querySelectorAll("#419177, #531703").addEventListener('change', function () {
var style = this.value == 'Sí' ? 'block' : 'none';
var style = this.value == 'Ok' ? 'block' : 'none';
var list = document.getElementsByClassName('option_type_419180') [0].style.display = style;
var list = document.getElementsByClassName('option_type_531704') [0].style.display = style;
});
<select id="419177" name="properties[Customize 1?]"><option value="">  Customize 1?--</option><option value="Sí">Sí</option><option value="No">No</option></select>

<div class="option_type_419180" data-parent-id="419180">
Available colors </div>

<hr>

<select id="531703" name="properties[Customize 2?]"><option value="">  Customize 2?--</option><option value="Ok">Ok</option><option value="No">No</option></select>

<div class="option_type_531704" data-parent-id="419180">
Available colors 2</div>


Solution

  • The issue is because the first character of an identifier is numeric, see more info in this post:

    More info about first character of an identifier numeric

    Also you need to addEventListener to each element individually.

    Tip: Assign the result to document.querySelectorAll to a const or var or let, helps you to debugging the code, because you could place breakpoints and see it they have the right values.

      <script>
    const selects = document.querySelectorAll("[id='419177'], [id='531703']")  
    selects.forEach(select => {
        select.addEventListener('change', function () {
        var style = this.value == 'Sí' ? 'block' : 'none';
        var style = this.value == 'Ok' ? 'block' : 'none';
        var list = document.getElementsByClassName('option_type_419180')[0].style.display = style;
        var list = document.getElementsByClassName('option_type_531704')[0].style.display = style;
     });
    
    })
    </script>