检查单选按钮组是否至少选择了一个
Check if group of Radio-Buttons has at least one selected
我的反馈表单有问题。我想用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
,但这使我返回了undefined
值
您可以向每组单选按钮添加一个类,然后使用getelementscyclass或queryselectorall(与旧浏览器兼容)。根据您试图支持的内容,您也可以考虑在单选按钮上使用HTML5"required"属性。这将适用于大多数比IE8更新的浏览器,并且需要最少的代码。
我不能发表评论,所以我要澄清的是,目前发布在这里的另一个解决方案将不起作用,因为它会进行检查,以确保页面上至少有一个单选按钮已被选中,这意味着如果有多组单选按钮,用户可以提交不完整的表单。他的代码看起来是有效的,否则,只需为每组单选按钮创建一个类。
我认为这是您的最佳选择:
var selectedCount = 0;
$('.radio').each(function(){
if($(this).attr("checked", "checked")){
selectedCount++;
}
})
返回选中单选按钮的数量:
$('input:radio:checked').length
检查它是否等于单选按钮组的数量。(在你的例子中,有两个。)
Fiddle
试试这个解决方案:
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
}
}
变量"valid"表示整个表单有效(每组中至少选择一个单选按钮)。
这是一把小提琴。
相关文章:
- 在Twitter BootStrap嵌套下拉列表中托管一个选择列表(IE 9特定)
- HTML-使用mysql.php生成一个选择框.我怎样才能更改“;值“;生成的选择框选项的
- 我如何创建一个选择器,就像jQuery有jQuery()或$()一样
- 如何根据另一选择中的选择设置一个选择中的文本
- 正在尝试创建一个选择选项
- 在javascript中动态添加一个选择下拉菜单
- 当用户设置另一个选择值时,如何通过 Javascript 设置另一个选择值
- 从另一个选择框并使用数据库连接填充选择框
- 使用jquery创建并复制一个选择框
- 进行一个选择,自动发送表单并打开另一个选择(CodeIgniter)
- 使用jquery克隆一个选择菜单
- Jquery #id ul li 一个选择
- Chrome:在用户打开一个选择后添加选项
- 如果所有单选框在jQuery中都有一个选择,则显示一个元素
- 从select中选择一个选项,然后使用Codeigniter在另一个选择框上显示数据
- 将选择下拉列表发送到另一个选择下拉列表
- JQuery以基于另一个选择列表填充选择列表
- 在填充另一个选择框时动态添加选择框
- 两个表单,一个选择/下拉框-需要将选择值从一个表单复制到另一个表单
- 根据第一个选择框中选择的内容筛选下一个选择框的值