JavaScript将选择菜单选项附加到div标签

时间:2014-03-22 15:43:18

标签: javascript html drop-down-menu appendchild

作为JavaScript中的一个完整新手,我想出了如何从下拉菜单中显示所选对象的数量<div>。但我想弄清楚如何使下拉菜单中选中的文字出现在<div>

<script type="text/javascript">
window.onload = function() {
    var eSelect = document.getElementById('question1');
    var optOtherReason = document.getElementById('displayresponse');
    eSelect.onchange = function() {
        if(eSelect.selectedIndex === 2) {
            optOtherReason.style.display = 'block';

            var li = document.createElement("li");
            li.innerHTML = eSelect.selectedIndex;
            var ul = document.getElementById("appendedtext");
            ul.appendChild(li); 

        } else {
            optOtherReason.style.display = 'none';
        } 
    } 
}  

<body>
<select id="question1" name="question">
    <option value="x">Reason 1</option>
    <option value="y">Reason 2</option>
    <option value="other">Other Reason</option>
</select>
<div id="displayresponse" style="display: none;">Response here</div>
<ol id="appendedtext"> </ol>

2 个答案:

答案 0 :(得分:1)

var options = document.getElementsByTagName("option")options[eSelect.selectedIndex].innerHTML;结合使用,如下所示:

window.onload = function() {
    var eSelect = document.getElementById('question1');
    var optOtherReason = document.getElementById('displayresponse');

    // the option elements
    var options = document.getElementsByTagName("option");

    eSelect.onchange = function() {
        if(eSelect.selectedIndex === 2) {
            optOtherReason.style.display = 'block';

            var li = document.createElement("li");

            // eSelect.selectedIndex is the index (call it `n`) of the option
            // get that `n`-th option element from `options`
            // get its `.innerHTML`
            // and set to `li.innerHTML`
            li.innerHTML = options[eSelect.selectedIndex].innerHTML;

            var ul = document.getElementById("appendedtext");
            ul.appendChild(li);
        } else {
            optOtherReason.style.display = 'none';
        } 
    } 
}  

编辑:

如果要显示每个更改:

  1. 在有序列表中 - http://jsfiddle.net/GaurangTandon/6h9TT/3/
  2. 位于div - http://jsfiddle.net/GaurangTandon/6h9TT/4/

答案 1 :(得分:0)

我就是这样做的:

var select = document.getElementById('question1'),
    response = document.getElementById('displayresponse');
select.onchange = function() {
    var selectedOption = select.options[select.selectedIndex].innerHTML;
    response.innerHTML = selectedOption;
    response.style.display = 'inline';
}

Fiddle