有没有一种方法可以使用JavaScript来使用按钮切换选择菜单中的选项?

huangapple go评论58阅读模式
英文:

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?

&lt;html&gt;

&lt;head&gt;

&lt;/head&gt;

&lt;body&gt;

&lt;button id=&quot;flavorBtn&quot; class=&quot;flavorBtn&quot;&gt;Toggle Flavors&lt;/button&gt;&lt;br&gt;&lt;br&gt;

&lt;select name=&quot;flavor&quot; id=&quot;selectField&quot;&gt;
    &lt;option value=&quot;Vanilla&quot;&gt;Vanilla&lt;/option&gt;
    &lt;option Value=&quot;Chocolate&quot;&gt;Chocolate&lt;/option&gt;
&lt;/select&gt;

&lt;/body&gt;

&lt;/html&gt;

答案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(&#39;#selectField&#39;)
document.querySelector(&#39;#flavorBtn&#39;).addEventListener(&#39;click&#39;, () =&gt; {
  select.selectedIndex = (select.selectedIndex + 1) % select.options.length
})

<!-- language: lang-html -->

&lt;button id=&quot;flavorBtn&quot; class=&quot;flavorBtn&quot;&gt;Toggle Flavors&lt;/button&gt;&lt;br&gt;&lt;br&gt;

&lt;select name=&quot;flavor&quot; id=&quot;selectField&quot;&gt;
    &lt;option value=&quot;Vanilla&quot;&gt;Vanilla&lt;/option&gt;
    &lt;option Value=&quot;Chocolate&quot;&gt;Chocolate&lt;/option&gt;
&lt;/select&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 04:37:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75355346.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定