2 回答
TA贡献1818条经验 获得超3个赞
假设有多个问题,正如您在问题下的评论中所述,那么您只需要检查.ans元素总数是否与.ans包含已检查无线电的元素数相匹配,如下所示:
$("#sub").click(function() {
var $answers = $('.ans');
var valid = $answers.length == $answers.filter(':has(:radio:checked)').length;
if (valid ) {
$("#form1").submit();
} else {
swal("Oops!", "Please select at least one answer in each question.", "error")
}
});
作为旁注,出于可访问性的原因,我建议您submit在form元素事件下执行此检查,而不是单击按钮。
TA贡献1779条经验 获得超6个赞
这是 - 一如既往 - 使用标准的 vanilla Javascript 很容易实现。不需要jQuery。
document.forms[0].addEventListener('submit', (event) => {
const check = [...document.forms[0].querySelectorAll('fieldset')].every(fieldset => !!fieldset.querySelector('input:checked'));
console.log(`${check ? 'A' : 'Not a'}ll questions have been answered!`);
// for demo purposes, prevent the submit regardless
event.preventDefault();
// in your code, you'd do the check
// if (!check) event.preventDefault();
})
form { display: flex; }
<form id="questions">
<fieldset>
<legend>What is 1+1?</legend>
<input type="radio" name="addition" id="addition1" value="3" />
<label for="addition1">3</label>
<br />
<input type="radio" name="addition" id="addition2" value="1" />
<label for="addition2">1</label>
<br />
<input type="radio" name="addition" id="addition3" value="2" />
<label for="addition3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1*1?</legend>
<input type="radio" name="multiplication" id="multiplication1" value="3" />
<label for="multiplication1">3</label>
<br />
<input type="radio" name="multiplication" id="multiplication2" value="1" />
<label for="multiplication2">1</label>
<br />
<input type="radio" name="multiplication" id="multiplication3" value="2" />
<label for="multiplication3">2</label>
<br />
</fieldset>
<fieldset>
<legend>What is 1-1?</legend>
<input type="radio" name="subtraction" id="subtraction1" value="-1" />
<label for="subtraction1">-1</label>
<br />
<input type="radio" name="subtraction" id="subtraction2" value="0" />
<label for="subtraction2">0</label>
<br />
<input type="radio" name="subtraction" id="subtraction3" value="1" />
<label for="subtraction3">1</label>
<br />
</fieldset>
<button type="submit">Submit</button>
</form>
添加回答
举报