I have the following code<hr>
HTML
<select id="select" placeholder="Choose Select" class="selectpicker" multiple></select>
<div class="container">
<div id="all" class="items">ALL</div>
<div id="1" class="items">Div_1</div>
<div id="2" class="items">Div_2</div>
<div id="3" class="items">Div_3</div>
<div id="4" class="items">Div_4</div>
<div id="5" class="items">Div_5</div>
<div id="6" class="items">Div_6</div>
</div>
Javascript
<hr>
var select = document.getElementById('select');
var elems = document.querySelectorAll('.items');
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) {
el.style.display = 'block';
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';
}
}
});
How can I add show all property when nothing is selected or I choose show all. Thank you!
I tried adding the condition and it didn't work. Please who can help me Thank You!
A quick and simple solution is to check the text of opt
for all
and then get all items and set the display
style to block
.
Disclaimer: Nested ifs
are pretty ugly and not best practice. So feel free to refacor. :D
if (opt.innerText === 'all') {
var items = document.getElementsByClassName('items');
for (i = 0; i < items.length; i++) {
items[i].style.display = 'block';
}
return;
}
var select = document.getElementById('select');
var elems = document.querySelectorAll('.items');
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) {
el.style.display = 'block';
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) {
if (opt.innerText === 'all') {
var items = document.getElementsByClassName('items');
for (i = 0; i < items.length; i++) {
items[i].style.display = 'block';
}
return;
}
document.getElementById(val).style.display = 'block';
} else {
document.getElementById(val).style.display = 'none';
}
}
});
<select id="select" placeholder="Choose Select" class="selectpicker" multiple></select>
<div class="container">
<div id="all" class="items">ALL</div>
<div id="1" class="items">Div_1</div>
<div id="2" class="items">Div_2</div>
<div id="3" class="items">Div_3</div>
<div id="4" class="items">Div_4</div>
<div id="5" class="items">Div_5</div>
<div id="6" class="items">Div_6</div>
</div>