我有一个表格,其中两个ro
具有相同的名称。当其中一个被要求和未被选中(因此无效)时,另一个也被定性为无效:
<input>
我希望第二个无线电输入有效。如何使<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<form id="form">
<input id="rad1" type="radio" name="my radio 3" value="option 1" required>
<input id="rad2" type="radio" name="my radio 3" value="option 2">
</form>
<script>
function checkValid() {
console.log('Should be valid form: ' + document.getElementById('form').checkValidity());
console.log('Rad1 should show false: ' + document.getElementById('rad1').checkValidity());
console.log('Rad2 should show true: ' + document.getElementById('rad2').checkValidity());
}
checkValid();
</script>
</body>
</html>
有效(即#rad2
返回checkValidity()
)?为什么这两个无线电之间的有效性有关?
我阅读了所有可能的MDN文档,但我找不到解释。
答案 0 :(得分:1)
根据需要设置单选按钮组时,要求是选择一个选项。如果要验证是否已选中特定选项,则需要使用var selected = document.querySelectorAll('#Rad1:checked');var isSelected = selected.length > 0 ? true: false;
请注意,在下面调整的片段中检查无线电时,它们都会更改为TRUE:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.3.js"></script>
</head>
<body>
<form id="form">
<input id="rad1" type="radio" name="my radio 3" value="option 1" required>
<input id="rad2" type="radio" name="my radio 3" value="option 2">
</form>
<script>
function checkValid() {
console.log('Should be valid form: ' + document.getElementById('form').checkValidity());
console.log('Rad1 should show false: ' + document.getElementById('rad1').checkValidity());
console.log('Rad2 should show true: ' + document.getElementById('rad2').checkValidity());
}
checkValid();
$('[name="my radio 3"]').on('change', function() {
checkValid();
})
</script>
</body>
</html>