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:
5
Answers
As a number of people have said in the comments, your “delicious food” and “healthy food” fields should be coded as radio buttons in your HTML, not as checkboxes. That way, you’ll get the correct behaviour without having to do anything.
However, if you want to, you can style the radio buttons to appear like checkboxes or anything else you like, really. These articles should help you out:
As some others have pointed out, using radio buttons might be a better option, but if you really want to use checkboxes, the code below can help you achieve your goal,
Please try this updated
Please Try this
Please try this code. I have used Form validation with Parsley
Add the Required on HTML Tag: