While there is plenty of answers I will just chip in with my solution that uses HTML required
attribute for native browser notifications.
As I see none of the answers use that, some use disable button and some disable form etc.
required
is set from the start on all elements and if one checkbox is checked required
is removed from all, if its set back to unchecked it sets all back to required
.
var form = document.getElementById('myForm');
var els = document.querySelectorAll('input[name="test"]');
form.onchange = function() {
for (var i = 0, len = els.length; i < len; i++) {
[].forEach.call(els, function(el) {
el.required = true;;
});
};
for (var i = 0; i < els.length; i++) {
if (els[i].checked) {
for (var i = 0, len = els.length; i < len; i++) {
[].forEach.call(els, function(el) {
el.removeAttribute("required");
});
};
}
}
};
form.onchange();
<form>
<div id="myForm">
<label>What is your favorite color?</label>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="test1" name="test" required>
<label class="custom-control-label" for="test1">Red</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="test2" name="test" required>
<label class="custom-control-label" for="test2">Green</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="test3" name="test" required>
<label class="custom-control-label" for="test3">Neither</label>
</div>
<button type="submit">Submit</button>
<div>
<form>
And now you got HTML radio buttons :)