gpt4 book ai didi

javascript - 验证测验的单选按钮

转载 作者:行者123 更新时间:2023-11-30 10:17:29 26 4
gpt4 key购买 nike

需要验证单选按钮正在开发一个测验页面我只能验证一组单选按钮任何帮助都很好下面是我的代码。如果用户在没有回答问题的情况下点击提交按钮,我希望显示一条警告消息,说你必须回答他们没有回答的任何问题。关于为什么 jquery 不能工作的任何想法谢谢

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>

<script type="text/javascript" src="js/jquery.js"></script>

<script type="text/javascript">
$('#quizForm').on('submit', function() {
var emptyCount = 0;
$('li').each(function() {
var found = false;
$(this).find('input[type=radio]').each(function() {
if ($(this).prop('checked')) {
found = true;
}
});
if (!found) {
emptyCount++;
}
});
if (emptyCount > 0) {
alert('Missing checks:' + emptyCount);
return false;
}
return true;
</script>


<form action='mail.php' method='post' id='quizForm' id='1' name='quizForm' onSubmit='form()'>
<ol>
<li>
<h3>1 x 1 =</h3>
<div>
<input type='radio' name='answerOne' id='answerOne' value='A' />
<label for='answerOneA'>A)1</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='B' />
<label for='answerOneB'>B)2</label>
</div>
<div>
<input type='radio' name='answerOne' id='answerOne' value='C' />
<label for='answerOneC'>C)3</label>
</div>
</li>
<li>
<h3>1 x 6 =</h3>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='A' />
<label for='answerTwoA'>A)5</label>
</div>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='B' />
<label for='answerTwoB'>B)6</label>
</div>
<div>
<input type='radio' name='answerTwo' id='answerTwo' value='C' />
<label for='answerTwoC'>C)4</label>
</div>
</li>
<li>
<h3>2 x 8 =</h3>
<div>
<input type='radio' name='answerThree' id='answerThree' value='A' />
<label for='answerThreeA'>A)14</label>
</div>
<div>
<input type='radio' name='answerThree' id='answerThree' value='B' />
<label for='answerThreeB'>B)12</label>
</div>
<div>
<input type='radio' name='answerThree' id='answerThree' value='C' />
<label for='answerThreeC'>C)16</label>
</div>
</li>
</ol>
<input type="submit" />
</form>

</body>
</html>

最佳答案

首先:您不应该在一个页面上多次使用相同的 ID。所以每个答案的id应该不同。

无论如何,您可以遍历所有 li 元素并检查其中是否有选中的 radio 。

$('form').on('submit', function() {
var emptyCount = 0;
$('li').each(function() {
var found = false;
$(this).find('input[type=radio]').each(function() {
if ($(this).prop('checked')) {
found = true;
}
});
if (!found) {
emptyCount++;
}
});
if (emptyCount > 0) {
alert('Missing checks');
return false;
}
return true;
});

关于javascript - 验证测验的单选按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23122499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com