Javascript - <option>中的onchange

sui*_*eek 11 html javascript

我有一个相对简单的形式,询问各种问题.其中一个问题通过选择框回答.我想要做的是,如果该人选择特定选项,则会提示他们提供更多信息.

在一些在线教程的帮助下,我设法让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>
Run Code Online (Sandbox Code Playgroud)

我想要的是如果他们选择"其他原因"然后显示div.如果onChange不能与Option标签一起使用,我不确定如何实现这一点!

任何帮助非常感谢:)

注意:当谈到Javascript时,请完成初学者,如果这很简单,我很抱歉!

Tom*_*Tom 17

设置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>
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会更进一步,将JavaScript移动到外部文件中,并将其包含在页面的标题中; 但是,出于所有意图和目的,这应该有助于回答您的问题.


sui*_*eek 9

在阅读了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>
Run Code Online (Sandbox Code Playgroud)

希望这有助于将来的其他人!


Tum*_*oid 6

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>
Run Code Online (Sandbox Code Playgroud)