Question

As a complete novice in JavaScript I figured out how to make the number of the selected objects from a drop down menu appear in a <div>. But I'm trying to figure out how to make the text selected in the drop menu appear in a <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>

Was it helpful?

Solution

Use var options = document.getElementsByTagName("option") in conjunction with options[eSelect.selectedIndex].innerHTML;, like this:

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';
        } 
    } 
}  

EDIT:

If you want to display every change:

  1. in the ordered list- http://jsfiddle.net/GaurangTandon/6h9TT/3/
  2. in the div - http://jsfiddle.net/GaurangTandon/6h9TT/4/

OTHER TIPS

This is how I would do it:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top