如何在多选下拉列表中只允许选择某些值的一个选项?

我想用以下选项制作一个下拉菜单。我希望能够为选项 A、B 和 C 选择一个多选值,但如果选择了选项 D,则禁用多选。我怎样才能做到这一点?谢谢。


<label>Choose an option:</label>

  <select required multiple>

    <option>Please select</option>

    <option value="A">A</option>

    <option value="B">B</option>

    <option value="C">C</option>

    <option value="D">C</option>

  </select>


慕神8447489
浏览 211回答 1
1回答

米脂

如果选择了“D”,则删除其他选定的选项,否则允许多选。{&nbsp; document.addEventListener("mouseup", checkMultiple);&nbsp; function checkMultiple(evt) {&nbsp; &nbsp; if (!/option/i.test(evt.target.nodeName)) {&nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }&nbsp; &nbsp; const selector = evt.target.parentNode;&nbsp; &nbsp; const options = [...selector.querySelectorAll("option")];&nbsp; &nbsp; if (options.find(v => v.value === "D").selected) {&nbsp; &nbsp; &nbsp; options&nbsp; &nbsp; &nbsp; &nbsp; .filter(v => v.value !== "D")&nbsp; &nbsp; &nbsp; &nbsp; .forEach(v => v.selected = false);&nbsp; &nbsp; }&nbsp; }}<label>Choose an option:</label><select required multiple>&nbsp; <option>Please select</option>&nbsp; <option value="A">A</option>&nbsp; <option value="B">B</option>&nbsp; <option value="C">C</option>&nbsp; <option value="D">D</option></select>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript