检查一组Radio-Buttons是否至少有一个被选中

时间:2015-11-03 14:34:22

标签: javascript jquery html

我的反馈表格出了问题。

我只想用Jquery或Javascript验证,在提交表单之前,每组单选按钮总是选择一个按钮。

这是我的form.html中的代码。

<form id='form' method='POST' action='validate.php'>
    <table>
        <!-- Table header -->
        <tr>
            <th>&nbsp;</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,但这给了我未定义的值

先谢谢

4 个答案:

答案 0 :(得分:0)

您可以为每组单选按钮添加一个类,然后使用getelementsbyclass或queryselectorall(与旧版浏览器兼容)。根据您尝试支持的内容,您还可以考虑使用HTML5&#34; required&#34;单选按钮上的属性。这适用于大多数比IE8更新的浏览器,并且您需要最少的编码。

我无法发表评论,所以我会澄清此时发布的其他解决方案无效,因为它会检查以确保页面上至少有一个单选按钮已经过检查,这意味着如果有多组单选按钮,则用户可以提交不完整的表单。他的代码看起来不像其他功能,只需为每组单选按钮创建一个类。

答案 1 :(得分:0)

我认为这是你最好的选择:

var selectedCount = 0;
$('.radio').each(function(){
    if($(this).attr("checked", "checked")){
        selectedCount++;
    }
})

答案 2 :(得分:0)

这将返回已检查单选按钮的数量:

$('input:radio:checked').length

检查它是否等于单选按钮组的数量。 (在你的例子中,两个。)

Fiddle

答案 3 :(得分:0)

试试这个解决方案:

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'表示整个表单有效(每组中至少选择一个单选按钮)。

这是jsfiddle