检查一组电台是否至少有一个选中
问题描述:
我的反馈表格出现问题。检查一组电台是否至少有一个选中
我只是想用jQuery或Javascript来验证,每一组的单选按钮始终一个按钮来选择,然后才能提交表单。
这是我的代码从我的form.html。
<form id='form' method='POST' action='validate.php'>
<table>
<!-- Table header -->
<tr>
<th> </th>
<th>Always</th>
<th>Often</th>
<th>Rarely</th>
<th>Never</th>
</tr>
<!-- Group One -->
<tr>
<th>Dummy Text 1</th>
<th><input class='radio' type='radio' name='item[0]' value='always'></th>
<th><input class='radio' type='radio' name='item[0]' value='often'></th>
<th><input class='radio' type='radio' name='item[0]' value='rarely'></th>
<th><input class='radio' type='radio' name='item[0]' value='never'></th>
</tr>
<!-- Group two -->
<tr>
<th>Dummy Text 2</th>
<th><input class='radio' type='radio' name='item[1]' value='always'></th>
<th><input class='radio' type='radio' name='item[1]' value='often'></th>
<th><input class='radio' type='radio' name='item[1]' value='rarely'></th>
<th><input class='radio' type='radio' name='item[1]' value='never'></th>
</tr>
<!-- End of table -->
</table>
</form>
<button class='buttons' onclick='subForm()' name='submit'>Send Feedback</button>
<script>
function subForm() {
//Code
}
</script>
但我不知道我应该用来检查是否检查无线电按钮。
我想document.getElementsByName
但这给我回不定值
由于提前
答
你可以添加一个类各组单选按钮,然后用getelementsbyclass,或queryselectorall(兼容旧版本浏览器) 。根据您要支持的内容,您还可以考虑在单选按钮上使用HTML5“required”属性。这将适用于大多数比IE8更新的浏览器,并且只需要最少的编码。
我不能评论,所以我会澄清的是,这里张贴在此刻其他的解决办法是行不通的,因为它会检查,以确保在页面上至少一个单选按钮被选中,这意味着用户可以如果有多组单选按钮,请提交不完整的表格。他的代码看起来是功能性的,否则,只需为每组单选按钮创建一个类。
答
尝试这种解决方案:
function subForm() {
var valid = true;
//for every row
jQuery("tr").each(function(idx, elem) {
//checks only rows with radio inputs inside
if ($(this).find('input[type=radio]').length) {
//if there are no radios checked then form is not valid
if (!$(this).find('input[type=radio]:checked').length) {
valid = false;
}
}
});
console.log(valid);
if (valid) {
//submit form
}
}
变量“有效”指的是整体形式是有效的(至少一个单选按钮每个组中选择的)。
这里有一个jsfiddle。
你有'getelementsbyclass'数组吗?或者你得到了什么输出? – Lino
噢,你的意思是'getElementsByClassName',因为你将无法正常工作:) – Lino
是的,我的意思是geElementsByClassName,我很懒惰,我通常依赖于我的开发环境/代码编辑器自动完成这样的事情对我来说。 –