I have the following code on my page that has few checkboxes.
<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>
Once the user clicks on the CatFood, I want the end user to click on either "Delicious Food" check box or "Healthy Food" check box, but not both. Only One of the check box is required. In order to accomplish this, I tried to write this code:
<script>
$(function(){
$('#CatFood').on('click', function () {
if($(this).is(':checked')){
$('.Food1').attr('required', 'required') || $('.Food2').attr('required', 'required');
}else{
$('.Food1').removeAttr('required');
}
});
});
</script>
Nothing is happening on click of the submit button. I can make the checkboxes radio button, but in my case, I want it to be check boxes. below is the screen shot:
below is the code for reported:
function reported(checkbox) {
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: