Alex Ianevski Alex Ianevski - 4 months ago 6
HTML Question

show multiple divs based on dropdown selection

The html file with certain number of divs (different every time) is generated aitomatically. For simplicity:

<div id="plate1">
<p>plate 1 info</p>
</div>
<div id="plate2">
<p>plate 2 info</p>
</div>
<div id="plate3">
<p>plate 3 info</p>
</div>
<div id="plate2">
<p>plate 2 additional info</p>
</div>


I am wondering about the possibility of dynamically filling a dropdown
<select multiple></select>
(based on unique block's ids):

enter image description here

And displaying only those divs, which are selected:

plate2 info
plate3 info
plate 2 additional info

Answer

Without using jQuery

var select = document.getElementById('select');
var elems = document.querySelectorAll('.plate');
var obj = {};
var filtered = [].filter.call(elems, function(el) {
  if (!obj[el.id]) {
    obj[el.id] = true;
    return true;
  } else {
    return false;
  }
});
var selectOpt = filtered.map(function(el) {
  return '<option>' + el.id + '</option>';
});
select.innerHTML = selectOpt.join('');
select.addEventListener('change', function() {
  for (var i = 0, iLen = select.options.length; i < iLen; i++) {
    var opt = select.options[i];
    var val = opt.value || opt.text;
    if (opt.selected) {
      document.getElementById(val).style.display = 'block';
    } else {
      document.getElementById(val).style.display = 'none';
    }
  }
});
div {
  display: none;
}
<div id="plate1" class="plate">
  <p>plate 1 info</p>
</div>
<div id="plate2" class="plate">
  <p>plate 2 info</p>
</div>
<div id="plate3" class="plate">
  <p>plate 3 info</p>
</div>
<div id="plate2" class="plate">
  <p>plate 2 additional info</p>
</div>

<select multiple id='select'></select>

Comments