繁体   English   中英

如何制作 2 个复选框,例如,如果选中一个,然后您尝试检查另一个,它会取消第一个?

[英]How do I make 2 checkboxes, that if for example one is checked and then you try to check the other it cancel the first one?

我的代码中有 2 个复选框: <input type = "checkbox" id = "soundyes" name = "soundyes" value = "soundyes">

<input type = "checkbox" id = "soundno" name = "soundno" value = "soundno">

例如,如果一个人检查了“soundyes”选项(soundyes.checked == true)然后尝试检查“soundno”选项,是否有可能取消选中第一个复选框(“soundyes”)(soundyes.checked == false) 在 JavaScript 中?

提前致谢!

您可以在两个复选框上使用处理更改事件。

 function uncheck(input){ input.checked = false; } let no = document.querySelector("#soundno") let yes = document.querySelector("#soundyes") yes.addEventListener("click", e=>{ uncheck(no) }); no.addEventListener("click", e=>{ uncheck(yes); })
 Checkbox 1: <input type = "checkbox" id = "soundyes" name = "soundyes" value = "soundyes"> Checkbox 2: <input type = "checkbox" id = "soundno" name = "soundno" value = "soundno">

 const y = document.querySelector('#yes'); const n = document.querySelector('#no'); const both = [y, n]; both.map(c => c.addEventListener('change', e => { both.filter(c => e.target.== c)[0].checked =.e;target;checked; }));
 <label> <input type="checkbox" id="yes" checked /> yes </label> <label> <input type="checkbox" id="no"/> no </label>



这应该工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM