I have a checkbox with 3 options (option 1, option 2, and option 3). In Javascript, I would like option 1 and option 2 to be required, if either option is selected, then the other is no longer required. Option 3 is always optional. Any ideas?
I’ve tried the following:
if ($('input[value="0"]', this).is(':checked') ||
$('input[value="1"]', this).is(':checked')) {
// everything's fine...
} else {
this.elem.find('input[value="0"]').prop('required', true);
this.elem.find('input[value="1"]').prop('required', true);
this.elem.find('input[value="2"]').prop('required', false);
}
and this (my thought was if nothing is selected then option 1 and 2 is required; ignoring the third option completely):
if ($myCheckbox.length === 0) {
$myCheckbox.elem.find('input[value="0"]').attr('required', 'required');
$myCheckbox.elem.find('input[value="1"]').attr('required', 'required');
} else {
$myCheckbox.elem.find('input[value="0"]').removeAttr('required');
$myCheckbox.elem.find('input[value="1"]').removeAttr('required');
}
and even something like this based on another dropdown:
$myCheckbox.elem.find('input[value="0"]').prop('required', $myDropdown.isSelected());
$myCheckbox.elem.find('input[value="1"]').prop('required', $myDropdown.isSelected());
but nothing works. What happens is that first two options are not being shown as required. Users can still submit my answers without touching the checkbox. Users cannot submit anything until either option 1 or option 2 is selected from a checkbox with 3 options
2
Answers
How about the HTML
required
attribute?this is a question about validation
sample code: