我的代码中使用了 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/