2015-09-07 55 views
1

我有一个简单的问题,但我尝试了很多事情,但他们不像我期望的那样工作。如何验证提交按钮上的复选框?

问题: 1.一些复选框的类有“a”,“b”,“c”但是id不同。 2.在按钮上单击我尝试验证是否仅选中了一个复选框。 3.我只知道复选框类(常见的元素)

我的代码:

$('#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!!!"); 
}); 

请给我解决这个问题

+1

你可以更新一些样本HTML你的问题? – usmanali

+3

“点击按钮,我尝试验证只有一个复选框被选中” - 为什么你首先使用复选框而不是单选按钮? – Quentin

+0

因为我必须@昆汀 – Adamo

回答

2

你使用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'); 
    } 
}); 
+0

工作得很好。谢谢 – Adamo

1
See this code it may be help you!
<input type = "checkbox" class = "a ownClass" id = "one"></input> 
<input type = "checkbox" class = "b ownClass" id = "two"></input> 
<input type = "checkbox" class = "c ownClass" id = "three"></input> 
<input type = "button" id = "submit" value = "submit"></input> 


    (function(){ 
     $("#submit").click(function(){ 
     var checked = []; 
     $(".ownClass").each(function(currIndex, val){ 
     if($(this).is(':checked')){ 
      checked.push(this.id); 
     } 

    }) 
    console.log(checked); 
    }); 
}()); 
+0

谢谢。但在我的情况@Popnoodles anserw是最好的:D – Adamo

相关问题