Is there an onclick javascript function which would allow me to toggle between two options in a select input, using a button?
<html>
<head>
</head>
<body>
<button id="flavorBtn" >Toggle Flavors</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">Vanilla</option>
<option Value="Chocolate">Chocolate</option>
</select>
</body>
</html>
CodePudding user response:
const select = document.querySelector('#selectField')
document.querySelector('#flavorBtn').addEventListener('click', () => {
select.selectedIndex = (select.selectedIndex 1) % select.options.length
})
<button id="flavorBtn" >Toggle Flavors</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">Vanilla</option>
<option Value="Chocolate">Chocolate</option>
</select>