jquery - 遍历单选按钮组并显示错误

标签 jquery css

我的代码中使用了 4 个 radio 组。其中 2 个是必需的 radio 组。在提交表格时,我需要检查是否选中了所需的 radio 组。如果没有选中,我需要在下一个 div 中添加一条错误消息。但这对我不起作用。有人可以帮助我吗? 下面是一个广播组。所以我试图遍历单选按钮并检查它是否未选中,添加错误消息。但它似乎没有用。两个单选按钮都会显示“请选择一个”文本。我只需要在第二个单选按钮下方的一个位置。

$("input:radio").each(function(){
 $(this).next('div.error').remove();
var name = $(this).attr("name");
if($("input:radio[name="+name+"]:checked").length == 0){
    $(this).after('<div class="error">Please select one</div>');
    returnValue = false;
}
else{
    $(this).next('div.error').remove();
    returnValue = true;
}   

});

HTML

 <input name="radio1" id="one" value="first" type="radio" class = "check"/>
 <input name="radio1" id="two" value="second" type="radio" class="check"/>

最佳答案

尝试

var requiredgroups = ['name1', 'name2'], returnValue = true;

$.each(requiredgroups, function(id, name){
    var $radios = $('input[name="' + name + '"]:radio');
    $radios.last().next('div.error').remove();

    if(!$radios.filter(':checked').length){
        $radios.last().after('<div class="error">Please select one</div>');
        returnValue = false;
    }
})

演示:Fiddle

关于jquery - 遍历单选按钮组并显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19379894/

相关文章:

javascript - jQuery 选择器速度

javascript - 如何让一系列元素循环显示一次只显示一个

html - 当只应显示错误布局时显示输入焦点

javascript - jQuery 不拾取嵌套标签值的分页

javascript - 从 Combo Cox( View )获取值并发送到 Controller 而不加载页面

javascript - 如何更改 reddit 的嵌入评论 iframe 的最大宽度?

jquery - 如何应用使用 jQuery 动态加载的内联和/或外部 CSS

php - 如何仅在使用php动态生成的tr的最后一行设置背景颜色

javascript - jQuery Sortable - 允许将某些项目仅放入某些列表中

css - Browsersync 和/或 Gulp 不断重置 CSS