OneLag OneLag - 5 days ago 6
Javascript Question

Tables loading on a dropdown

I have a dropdown and I want to make different tables appear below it, according to the selected option.

I've already seen it here:
Javascript - onchange within <option>

I was able to replicate that, but I really don't know how to add more options/tables.

Can someone help? This is the code so far:

<html>
<head>
<script type="text/javascript">
window.onload = function() {
var eSelect = document.getElementById('transfer_reason');
var optOtherReason = document.getElementById('otherdetail');
eSelect.onchange = function() {
if(eSelect.value === "other") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
var optOtherReason = document.getElementById('other2');
eSelect.onchange = function() {
if(eSelect.value === "z") {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="">Motivo</option>
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="z">Reason 3</option>
<option value="other">Other Reason</option>
</select>
<br>
<table border="1" id="otherdetail" style="display: none;">
<tr>
<th>Versão 11</th><th>Versão 12</th><th>Justificativas</th>
</tr>
<tr>
<td> 1</td><td>Angelina</td><td>Delhi</td>
</tr>
</table>

<table border="1" id="other2" style="display: none;">
<tr>
<th>Versão 11</th><th>Versão 12</th><th>Justificativas</th>
</tr>
<tr>
<td> 1</td><td>Galeno</td><td>Delhi</td>
</tr>
</table>
</body>
</html>


As it is now, only the table with id="other2" is loading correctly, while the other table is not.

Answer

There's a better way than what exists in the example. If you use the table ID values in your drop-down the whole thing gets easier.

<script type="text/javascript">
    window.onload = function() {
    var eSelect = document.getElementById('transfer_reason');
    var selVal;
    hideTables();
    eSelect.onchange = function() {
        hideTables();    
         selVal = eSelect[eSelect.selectedIndex].value;
        document.getElementById(selVal).style.display = "block";
    }

}

function hideTables() {
     var tables = document.getElementsByTagName("table");
    for(var x=0;x<tables.length;x++) {
        tables[x].style.display = "none";
    }
}    
 </script>

HTML:

  <select id="transfer_reason" name="transfer_reason">
        <option value="">Motivo</option>
        <option value="Table1">Reason 1</option>
        <option value="Table2">Reason 2</option>
        <option value="Table3">Reason 3</option>
        <option value="Table4">Other Reason</option>
</select>

<table id="Table1"><tr><td>#1#</td></tr></table>

<table id="Table2"><tr><td>#2#</td></tr></table> 

... etc ...
Comments