I have a HTML select with 3 options as following -
<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.
CodePudding user response:
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. 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.
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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
Increment the selectedIndex
of the select
, wrapping around when you get to the end.
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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>