Display elements with id matching select value and hide others [closed]

Pure JavaScript. There is no need of using IDs for every div element. Better use data attribute.

document.getElementById('dataSelect').addEventListener('change', function() {
  var nodes = document.querySelectorAll("div[data-amount]");
  var selected = this.options[this.selectedIndex];
  if (selected.value == "any") {
    for (var i = 0; i < nodes.length; i++) {
      nodes[i].style.display = 'block';
    }
  } else {
    for (var i = 0; i < nodes.length; i++) {
      nodes[i].style.display = (nodes[i].dataset.amount == selected.value) ? 'block' : 'none';
    }
  }

});
<select name="dataSelect" id="dataSelect" class="enter-drop" required>
<option value="" disabled>Data Amount</option>
<option value="any" selected>Any</option>
<option value="30">30GB</option>
<option value="12">12GB</option>
<option value="8">8GB</option>
</select>

<div data-amount="30" class="deal">30GB of Data</div>
<div data-amount="12" class="deal">12GB of Data</div>
<div data-amount="8" class="deal">8GB of Data</div>

Browse More Popular Posts

Leave a Comment