0

我的代码中使用了 4 个无线电组。其中 2 个是必需的无线电组。在提交表格时,我需要检查是否检查了所需的无线电组。如果未选中,我需要在下一个 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"/>
4

2 回答 2

0

尝试

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;
    }
})

演示:小提琴

于 2013-10-15T11:22:03.987 回答
0

您也可以尝试以下实现。此实现使用组 div,您可以在其中添加数据验证属性。然后,javascript 使用此数据验证属性来了解它必须验证哪些组。我认为这是一个更好的实现,因为它很容易在其他页面/网站/应用程序上重用。

HTML:

<div class="group" data-validation="required">
<label><input name="radio1" value="first" type="radio" class = "check"/> First</label><br />
<label><input name="radio1" value="second" type="radio" class = "check"/>Second</label></div>

JavaScript:

jQuery(document).ready(function($) {

// Bind validate function
$('button').on('click', validate);


function validate() {
    $('.error').remove();
    $.each($('.group[data-validation=required]'), function (idx, group) {
        var current = $(group).find('[type=radio]:checked').val()
        if( current === undefined ) {
            $(group).after('<div class="error">Please select one</div>');
        }
    });
}});

演示小提琴

于 2013-10-15T11:43:00.467 回答