2012-11-05 102 views
0

這是我的代碼:我需要驗證複選框

<script>       
function validate(form) { 
    fail = validate_department(form); 
    if (fail == "") { 
     return true; 
     } else { 
      alert(fail); 
      return false; 
     } 
    } 
</script> 
<script> 
    function validate_department(form) { 
     if(!(form.operations.checked == true) && !(form.marketing.checked == true) && !(form.training.checked == true)){ return "You must enter at least one of the following: marketing, training, or operations.\n"; 
     } 
     return ""; 
    } 

</script> 
<form method="post" action="checkbox.php" onSubmit="return validate(this)"> 
<input type="checkbox" name="operations" value="operations" /> Operations <br> 
         <input type="checkbox" name="marketing" value="marketing" /> Marketing <br> 
         <input type="checkbox" name="training" value="training" /> Training 
<input id="submit" type="submit" name="submit" value="Signup" />       
</form> 

如果我不檢查任何我想要得到的消息告訴我,我必須檢查的至少一個。

+1

您的代碼正在工作。有什麼問題 – polin

+1

檢查這個http://jsfiddle.net/TfJZM/,它的工作 – Sibu

回答

0

試試這個validate函數。

function validate(form) { 
    fail = validate_department(form); 
    if (fail == "") { 
     for (var i = 0; i < form.elements.length; i++) { 
      if (form.elements[i].type && (form.elements[i].type.toLowerCase() == 'checkbox')) { 
       fail = "Please tick a checkbox at least one."; 
       break; 
      } 
     } 
    } 
    if (fail != "") { 
     alert(fail); 
     return false; 
    } else { 
     return true; 
    } 
} 
+0

這樣做,謝謝! – jimeast