Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
440 views
in Technique[技术] by (71.8m points)

html - Javascript - onchange within <option>

I have a relatively simple form which asks a variety of questions. One of those questions is answered via a Select Box. What I would like to do is if the person selects a particular option, they are prompted for more information.

With the help of a few online tutorials, I've managed to get the Javascript to display a hidden div just fine. My problem is I can't seem to localise the event to the Option tag, only the Select tag which is no use really.

At the moment the code looks like (code simplified to aid clarity!):

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

What I would like is if they choose "Other Reason" it then displays the div. Not sure how I achieve this if onChange can't be used with the Option tag!

Any assistance much appreciated :)

Note: Complete beginner when it comes to Javascript, I apologise if this is stupidly simple to achieve!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Setup the onchange event handler for the select box to look at the currently selected index. If the selected index is that of the 'Other Reason' option, then display the message; otherwise, hide the division.

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

Personally, I'd take it a step further and move the JavaScript into an external file and just include it in the header of the page; however, for all intents and purposes, this should help answer your question.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...