我有一个包含 3 个选项的复选框(选项 1、选项 2 和选项 3)。在Javascript中,我希望选项1和选项2是必需的,如果选择其中一个选项,则不再需要另一个。选项 3 始终是可选的。有什么想法吗?
我尝试过以下方法:
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);
}
这个(我的想法是,如果没有选择任何内容,则需要选项 1 和 2;完全忽略第三个选项):
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');
}
甚至是基于另一个下拉菜单的类似内容:
$myCheckbox.elem.find('input[value="0"]').prop('required', $myDropdown.isSelected());
$myCheckbox.elem.find('input[value="1"]').prop('required', $myDropdown.isSelected());
但没有任何作用。
HTML
required
属性怎么样?
function myFunction(){
document.querySelectorAll("input").forEach(function(element){
//element.checkValidity();
element.reportValidity()
})
}
<label>
en
<input type=radio name=language required>
</label>
<label>
fr
<input type=radio name=language required>
</label><br>
<input type=checkbox>
<button onclick=myFunction()>check validity</button>