我的页面上有以下代码,几乎没有复选框.
<form>
<input type="checkbox" id="CatFood" /><b>Cat Food</b><br /><br />
<input type="checkbox" id="Food1" name="test222" onclick="reported(this)" />Delicious Food<br />
<input type="checkbox" id="Food2" name="test222" onclick="reported(this)" />Healthy Food<br /><br /><br />
<button type="submit">Submit</button>
</form>
一旦用户点击cat 粮,我希望终端用户点击"美味食品"复选框或"健康食品"复选框,但不能同时点击两者.只需要其中一个复选框.为了实现这一点,我try 编写以下代码:
<script>
$(function(){
$('#CatFood').on('click', function () {
if($(this).is(':checked')){
$('.Food1').attr('required', 'required') || $('.Food2').attr('required', 'required');
}else{
$('.Food1').removeAttr('required');
}
});
});
</script>
单击提交按钮时没有任何react .我可以使复选框单选按钮,但在我的例子中,我希望它是复选框.以下是屏幕截图:
以下是已报告的代码:
报告的函数(复选框){
var checkboxes = document.getElementsByName('test222')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
I already looked at the following stack overflow link, but that did not help: