简体   繁体   中英

Get the value of select class options

I'm working on a test/quiz and I can't solve a problem.

I like to grab the selected value from a option and print it to the result p.

 <div class="add">
            <div class="add__container">
                <select class="add__type">
                    <option value="0" id="a01" selected>No</option>
                    <option value="1" id="a02">Ocassionally</option>
                    <option value="2" id="a03">Yes</option>
                </select>
            </div>
        </div>

    <button class="btn" onclick="myValue()">Results</button>
    <p id="result">... </p>

And here is my Javascript code where I'm stucked:

function myValue(){    
var e = document.getElementById("s01");
var value = e.options[e.selectedIndex].value;
var text = e.options[e.selectedIndex].text;

document.getElementById('result').innerHTML = e;

};

    

我认为您想将所选选项的实际文本放在 innerHtml 而不是选项 DOM 元素中:

document.getElementById('result').innerHTML = text;

Maybe you want this? I added the id "s01" on select.

<div class="add">
    <div class="add__container">
        <select id="s01" class="add__type">
            <option value="0" id="a01" selected>No</option>
            <option value="1" id="a02">Ocassionally</option>
            <option value="2" id="a03">Yes</option>
        </select>
    </div>
</div>

<button class="btn" onclick="myValue()">Results</button>
<p id="result">... </p>
<script>
    function myValue() {
        var e = document.getElementById("s01");
        var value = e.options[e.selectedIndex].value;
        var text = e.options[e.selectedIndex].text;
        document.getElementById('result').innerHTML = text;

    };
</script>

 // Unimportant stuff const $ = document; $.get = $.getElementById; $.get('theOptions').addEventListener('change', function(event) { // Get the value from the select-element $.get('out').innerHTML = 'You selected ' + event.target.value; // Or $.get('theOptions').value });
 <select id="theOptions"> <option value="o1">Option 1</option> <option value="o2">Option 2</option> <option value="o3">Option 3</option> </select> <span id="out">Nothing selected</span>


try this code. I think this code work like you requirement.

 function myValue(){ var select = document.getElementsByClassName("add__type")[0].value; document.getElementById('result').innerHTML = select; };
 <div class="add"> <div class="add__container"> <select class="add__type"> <option value="0" id="a01" selected>No</option> <option value="1" id="a02">Ocassionally</option> <option value="2" id="a03">Yes</option> </select> </div> </div> <button class="btn" onclick="myValue()">Results</button> <p id="result">... </p>

something more..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM