[英]Javascript - onchange within <option>
我有一個相對簡單的形式,詢問各種問題。 其中一個問題通過選擇框回答。 我想要做的是,如果該人選擇特定選項,則會提示他們提供更多信息。
在一些在線教程的幫助下,我設法讓Javascript顯示一個隱藏的div就好了。 我的問題是我似乎無法將事件本地化為Option標簽,只有Select標簽真的沒用。
目前代碼看起來像(簡化代碼以幫助清晰!):
<select id="transfer_reason" name="transfer_reason onChange="javascript:showDiv('otherdetail');">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
我想要的是如果他們選擇“其他原因”然后顯示div。 如果onChange不能與Option標簽一起使用,我不確定如何實現這一點!
任何幫助非常感謝:)
注意:完成初學者的Javascript,如果這很簡單,我很抱歉!
為選擇框設置onchange
事件處理程序以查看當前選定的索引。 如果所選索引是“其他原因”選項的索引,則顯示該消息; 否則,隱藏分裂。
<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.selectedIndex === 2) {
optOtherReason.style.display = 'block';
} else {
optOtherReason.style.display = 'none';
}
}
}
</script>
</head>
<body>
<select id="transfer_reason" name="transfer_reason">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
</body>
</html>
就個人而言,我會更進一步,將JavaScript移動到外部文件中,並將其包含在頁面的標題中; 但是,出於所有意圖和目的,這應該有助於回答您的問題。
在閱讀了Tom的精彩回應之后,我意識到如果我在表單中添加了其他選項,它就會破壞。 在我的例子中,很有可能,因為可以使用php管理面板添加/刪除選項。
我做了一點閱讀並稍微改了一下,以至於不是使用selectedIndex,而是使用值代替。
<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';
}
}
}
</script>
希望這有助於將來的其他人!
Tom的答案很優雅,整齊地將JS從HTML標記中移開。 如上所述,它甚至可以移動到外部文件。 然而,它為代碼添加了相當多的“無意義”,例如多個匿名函數賦值等。
如果你想要快速解決方案,你也可以將它全部放在select標簽內的onchange()中。 選擇你認為更合適的那個。
<select id="transfer_reason" name="transfer_reason" onchange="document.getElementById('otherdetail').style.display = (this.selectedIndex === 2) ? 'block' : 'none';">
<option value="x">Reason 1</option>
<option value="y">Reason 2</option>
<option value="other">Other Reason</option>
</select>
<div id="otherdetail" style="display: none;">More Detail Here Please</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.