我有一个简单的问题,但我尝试了很多方法,但它们没有按我的预期工作。
问题: 1. 一些复选框,其类如“a”、“b”、“c”,但具有不同的 id。 2. 单击按钮时,我尝试验证是否仅选中了一个复选框。 3.我只知道复选框类(公共(public)元素)
我的代码:
$('#submit').click(function() {
var matches = [];
var items = document.getElementsByClassName('1'); //??? if the items is null?
for (var i = 0; i < items.length; i++){
matches.push({id:items[i].id, value:items[i].value});
}
if((matches[0].id != matches[1].id) &&(matches[0].value == matches[1].value))
alert("ERROR!!!");
});
请告诉我解决该问题的最佳方法
最佳答案
您正在使用 jQuery。您希望使用类名“1”的复选框,就像它们是单选按钮一样,并且如果选中多个复选框,则发出错误警报。您的classname is invalid ,很可能您应该在表单提交上检查这一点,但这是您正在寻找的代码。
$('#submit').click(function() {
if ($('.1:checked').length > 1) alert('error');
});
...我想您也想在这种情况下阻止按钮提交表单:
$('#submit').click(function(e) {
if ($('.1:checked').length > 1) {
e.preventDefault();
alert('error');
}
});
关于jquery - 如何验证提交按钮上的复选框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32438129/