2012-02-16 44 views
0

我想检查用户输入greater than 2less than 4复选框被选中。如何检查< 2 and > 4在javascript中的复选框

我必须在表单提交之前做这个检查。

尽管我使用AlloyUI进行客户端验证。你可以用香草javascript来帮助我。

请帮我看看我的代码...

<% for(loop here which generates more than one checkbox) { %> 
<form name=".." method=".." action=".." onSubmit="return checkBox();"> 
    <input type="checkbox" id=".." name=".."/> 
</form> 
%> 

我的JavaScript

function checkBox(){ 
     alert("start"); 
     var total = 0; 
     var max = form.checkcompare.length; 
     alert(max); 
     for(var idx = 0; idx < max; idx++) 
     { 
     if(eval("document.compareform.checkcompare[" + idx + "].checked") == true) 
     { 
      alert("checking"); 
     total += 1; 
     } 
     } 
     if (total==2 || total==4) 
     { 
     /* document.compareform.submit(); */ 
     alert("success"); 
     } 
     else 
     { 
      alert('Select minimum of 2 or maximum of 4 Estimates'); 
     } 
     //alert("You selected " + total + " boxes."); 
     } 

它不是working..can有人help..Thanks

回答

1
function getNumberOfCheckedCheckboxes (form) { 
    var returnValue = 0; 
    var inputElements = form.getElementsByTagName("input"); 
    for (var i = 0; i < inputElements.length; i ++) { 
    if (inputElements.type == "checkbox") { 
     if (inputElments.checked) { 
     returnValue ++; 
     } 
    } 
    } 
    return returnValue; 
} 
1

东西告诉我,你不知道你在做什么。

首先,您正在为每个复选框创建一个表单。打开表单标签,然后放入循环添加复选框,然后关闭表单。

现在你的脚本...

form是不确定的,这样你就可以得到它的元素。 form.checkcompare是未定义的,所以你不能得到它的长度。您可能想要在onSubmit事件(onSubmit="return checkBox(this);")和function checkBox(form)中通过this。然后使用form.querySelectorAll('input[type=checkbox]');

接下来,为什么在世界上你使用邪恶eval只是为了获得数组索引?

如果这还不够,你说你想要“2至4”,但你的代码认为“3”无效。

最后,你不是return什么。

固定的(改善)代码:

function checkBox(form){ 
    var total = 0; 
    var boxes = form.querySelectorAll('input[type=checkbox]:checked').length; 
    if (boxes < 2 || boxes > 4) 
     return true; 
    else { 
     alert('Select minimum of 2 or maximum of 4 Estimates'); 
     return false; 
    } 
} 
+0

我有它的权利在我的代码。形式,然后循环内。 我尝试了你的代码,表单也没有任何提醒。你能帮我一个好心情吗?如果可以的话,请发送我的整个HTML。因为我必须改变AUI ...这应该帮助我gr8交易。 – 2012-02-16 19:21:55