英文:
Is there a way to toggle options in a select menu with a button, using javascript?
问题
<html>
<head>
</head>
<body>
<button id="flavorBtn" class="flavorBtn">切换口味</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">香草</option>
<option value="Chocolate">巧克力</option>
</select>
</body>
</html>
英文:
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" class="flavorBtn">Toggle Flavors</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">Vanilla</option>
<option Value="Chocolate">Chocolate</option>
</select>
</body>
</html>
答案1
得分: 1
const select = document.querySelector('#selectField')
document.querySelector('#flavorBtn').addEventListener('click', () => {
select.selectedIndex = (select.selectedIndex + 1) % select.options.length
})
<button id="flavorBtn" class="flavorBtn">切换口味</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">香草</option>
<option value="Chocolate">巧克力</option>
</select>
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const select = document.querySelector('#selectField')
document.querySelector('#flavorBtn').addEventListener('click', () => {
select.selectedIndex = (select.selectedIndex + 1) % select.options.length
})
<!-- language: lang-html -->
<button id="flavorBtn" class="flavorBtn">Toggle Flavors</button><br><br>
<select name="flavor" id="selectField">
<option value="Vanilla">Vanilla</option>
<option Value="Chocolate">Chocolate</option>
</select>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论