简体   繁体   English

如何使用 js 在 HTML 选择选项之间切换

[英]How to switch between HTML Select options with js

I have a HTML select with 3 options as following -我有一个带有 3 个选项的 HTML 选择,如下所示 -

        <select id="list">
            <option value="environment" selected>Environment Facing (default)</option>
            <option value="user">User Facing</option>
            <option value="member">Member Facing</option>
        </select>

what I want to do is to toggle between these values with a button.我想要做的是用一个按钮在这些值之间切换。 is that possible?那可能吗? How can I toggle like if first option is selected and if I click button second option get selected and if second is selected after clicking again third gets selected.如果选择了第一个选项,如果我单击按钮第二个选项被选中,如果再次单击后选择第二个选项,则如何切换第三个选项。 is there any way I can do it.有什么办法可以做到。

Increment the selectedIndex of the select , wrapping around when you get to the end.增加selectselectedIndex ,当你到达最后时环绕。

 document.getElementById("button").addEventListener("click", function() { let list = document.getElementById("list"); let selected = list.selectedIndex; selected = (selected + 1) % list.length; list.selectedIndex = selected; }); document.getElementById("show").addEventListener("click", function() { let list = document.getElementById("list"); console.log(`Selected = ${list.value}`); });
 <select id="list"> <option value="environment" selected>Environment Facing (default)</option> <option value="user">User Facing</option> <option value="member">Member Facing</option> </select> <button id="button" type="button">Toggle</button> <button id="show" type="button">Show selected</button>

One approach could be getting the available values into an array, and finding the currently selected value's index in that array, increase it by one and see if you get a value.一种方法可能是将可用值放入数组中,然后在该数组中找到当前选定值的索引,将其增加 1 并查看是否获得值。 If you get undefined (which is what you get if you try to access an array element at a non-existing index), you instead go with the arrays's first element.如果您得到undefined (这是您尝试访问不存在索引处的数组元素时得到的结果),则改为使用数组的第一个元素。

 const list = document.getElementById('list'); const values = [...list.options].map(({value}) => value); document.getElementById("button").addEventListener("click", function() { const currentValue = list.value; list.value = values[values.indexOf(currentValue)+1] ?? values[0]; });
 <select id="list"> <option value="environment" selected>Environment Facing (default)</option> <option value="user">User Facing</option> <option value="member">Member Facing</option> </select> <button id="button" type="button">Toggle</button>

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

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