检查单选按钮组是否至少选择了一个

Check if group of Radio-Buttons has at least one selected

本文关键字:一个 选择 单选按钮 是否 检查      更新时间:2023-09-26

我的反馈表单有问题。我想用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,但这使我返回了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"表示整个表单有效(每组中至少选择一个单选按钮)。

这是一把小提琴。