<table>
<tr><tr>
<tr id = select>custom dropdown select tag <tr>
<tr id = div1><tr>
<tr id = div2><tr>
<tr id = div3><tr>
<tr id = div4><tr>
<tr><tr>
<tr><tr>
</table>
I was looking for an efficient way to use js. hidden, if getElementById(select) =1, only the tr tag with id 1 should be displayed, if getElementById(select) =3, id =div1,div2,div3 should be displayed and not 4. I'm currently writing an if else statement that goes something like this:
if(document.getelementbyid("select")value == 2){
document.getelementbyid("div1").hidden = false ;
document.getelementbyid("div2").hidden = false ;
document.getelementbyid("div1").hidden = true;
document.getelementbyid("div2").hidden = true;
}
else {
document.getelementbyid("div1").hidden = false ;
document.getelementbyid("div2").hidden = false ;
document.getelementbyid("div1").hidden = false ;
document.getelementbyid("div2").hidden = false ;
}
Similarly, I'm repeating for all values, but I'd like to know the most efficient way to do this, because I have many tr tags in the table with different ids that I want to change only with a specific 12 ids after select tag that has an id .
CodePudding user response:
Use classes or other features to group the elements.
const select = document.getElementById("select");
select.addEventListener('change', () => {
Array.from(document.getElementsByClassName("group")).forEach(el => { el.hidden = true; });
const value = select.value;
for (let i = 1; i <= value; i) {
document.getElementById("div" i).hidden = false;
}
});
<table>
<tr><tr>
<tr><td><select id="select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4" selected>4</option>
</select></td></tr>
<tr><td><div id="div1" >A</div></td></tr>
<tr><td><div id="div2" >B</div></td></tr>
<tr><td><div id="div3" >C</div></td></tr>
<tr><td><div id="div4" >D</div></td></tr>
<tr><tr>
<tr><tr>
</table>
CodePudding user response:
I think there is a mapping MAP to handle this situation is the best.
const ValueMap = {
1: {
'div1': true
}
}
elements.forEach(item => {
item.hidden = !!ValueMap(value)[item.id]
})
// if Elements of many
const elements2 = docments.querySelectAll('tr[id^='div']')
elements2.forEach(item => {
const id = item.id.replace(/[^0-9]/ig, "");
if ( id <= value) {
item.hidden = true
} else {
item.hidden = false
};
})