如何实现CatFood选中时单复选框必填校验(替代单选按钮)
复选框表单验证问题求助
我页面里有一段包含多个复选框的表单代码:
<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>
我的需求是:当用户勾选CatFood复选框时,必须勾选「Delicious Food」或「Healthy Food」中的一个,且不能同时勾选;我希望保留复选框形式,不使用单选按钮。
我尝试写了以下代码来实现验证逻辑,但点击提交按钮后完全没效果:
$(function(){ $('#CatFood').on('click', function () { if($(this).is(':checked')){ $('.Food1').attr('required', 'required') || $('.Food2').attr('required', 'required'); }else{ $('.Food1').removeAttr('required'); } }); });
另外,我已经实现了reported函数来控制不能同时勾选两个食物复选框:
function reported(checkbox) { var checkboxes = document.getElementsByName('test222') checkboxes.forEach((item) => { if (item !== checkbox) item.checked = false }) }
我已经参考过相关资料,但问题仍未解决,请求帮助。
内容的提问来源于stack exchange,提问作者rimi
相关产品推荐
相关产品推荐

