下面我有一个单选按钮组的示例,我试图验证它是否已被选中,我使用 .each()
函数的原因是添加额外的输入所以函数可以循环它们。 jsFiddle
HTML
<table class="application entitlement">
<tbody><tr>
<td><label for="entitlement">Yes</label><input type="radio" value="yes" name="entitlement"></td>
<td><label for="entitlement">No</label><input type="radio" value="no" name="entitlement"></td>
</tr>
</tbody>
</table>
<a href="#" class="send-application">Submit Application</a>
jQuery
$('body').on('click', '.send-application', function(e){
e.preventDefault();
var isFormValid = true;
$('input[name=entitlement]').each(function(index, elem){
if (!$(this).is(':checked').val()) {
$(this).css({'box-shadow': '0 0 5px rgba(255,0,0,0.4)'});
isFormValid = false;
} else {
$(this).css({'box-shadow': 'none'});
}
});
});
最佳答案
你的逻辑有问题。 isFormValid
将始终设置为 false
,因为您将永远无法检查单选组中的所有按钮。
不必循环遍历每个集合,只需检查整个集合以查看是否检查了任何一个:
var $radioButtons = $('input[name=entitlement]');
if ( !$radioButtons.filter(':checked').length ) {
isFormValid = false;
$radioButtons.css('box-shadow', '0 0 5px rgba(255, 0, 0, 0.4)');
} else {
$radioButtons.css('box-shadow', 'none');
}
Here's a fiddle
关于jquery - 使用 jQuery 验证单选按钮是否已被选中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23360322/