2012-09-18 82 views
1

我有一個下拉列表,並且我想根據選定的選項在其下方顯示不同的表格。在下拉列表中加載表

我已經看到它在這裏: Javascript - onchange within <option>

我能夠複製,但我真的不知道如何添加更多選項/表。

有人可以幫忙嗎?這是迄今爲止代碼:

<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> 

因爲它是現在,只使用id =「其它2」是正確加載,而其他表不表。

+1

請在你的問題直接發佈的代碼。您將在不久的將來刪除收件箱文件,然後它將會消失。 – HerrSerker

+0

你說你不知道如何添加更多的選項/表格......這是否意味着你不知道如何添加更多的HTML,或者它是你有問題的Javascript?而且,就像yunzen說的那樣,你應該發佈你的代碼。 –

+0

只是有問題的JS。我可以添加一個表格,但是當我想添加更多時失敗。 – OneLag

回答

1

有一個比例子中存在的更好的方法。如果您在下拉列表中使用表格ID值,則整個事情變得更加容易。

<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 ... 
+0

將立即嘗試,謝謝。 [測試] – OneLag

+0

工作作爲一種魅力。非常感謝你,Diodeus =] – OneLag

+0

好的,那麼請檢查正確的答案。 –