2014-01-30 171 views
1

它可以在jsfiddle(http://jsfiddle.net/A6qhc/)中使用,但不能作爲獨立頁面在瀏覽器中使用。我不知道爲什麼,這很簡單。請踢我。爲什麼jQuery的複選框驗證不起作用?

<html> 
<head> 
    <title>SOME TITLE</title> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script type="text/javascript"> 
$('form#my_form').click(function(){ 
    if (! $('input:checkbox')[0].checked){ 
     alert('Please check the box to agree with the terms and conditions.'); 
     return false; 
    } 
}); 

</script> 
</head> 
<div id="message-trigger" style="display: visible;"> 
    <p>Now that you completed the required steps you may proceed by agreeing and submitting payment.</p> 
    <form id="my_form" method="post" action=""> 
     <input name="confirmtandc" type="checkbox" value="agree">&nbsp;&nbsp;Please check to verify that you've read and agree with <a href="portal/24/content/tandc.pdf" target="_blank">CMCI terms and conditions</a>. 
     <input type="submit" name="submit" value="Proceed to Payment" /> 

</form> 
</div> 
</html> 
+1

因爲'$('form#my_form')'不會在腳本實例化時指向任何元素。 DOM尚未準備就緒... – War10ck

+0

文檔準備就緒,duh。謝謝@ War10ck。 – user3251618

回答

2

您的腳本需要在一個dom ready handler

jQuery(function() { 
    $('form#my_form').click(function() { 
     if (!$('input[name="confirmtandc"]').is(':checked')) { 
      alert('Please check the box to agree with the terms and conditions.'); 
      return false; 
     } 
    }); 
}) 

演示:Fiddle

注:在撥弄它默認的jsfiddle工作,因爲增加了腳本的window.onload處理器 - 第二個下拉在左側面板