繁体   English   中英

获取选择类选项的值

[英]Get the value of select class options

我正在做一个测试/测验,但我无法解决问题。

我喜欢从选项中获取选定的值并将其打印到结果 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>

这是我卡住的 Javascript 代码:

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;

也许你想要这个? 我在选择时添加了 ID“s01”。

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


试试这个代码。 我认为这段代码符合您的要求。

 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>

还有一些..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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