2012-02-16 41 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

相關問題