为什么这个jquery复选框验证不起作用?

时间:2014-01-30 04:58:30

标签: jquery

它适用于jsfiddle(http://jsfiddle.net/A6qhc/),但不适用于浏览器中的独立页面。我不知道为什么,这很简单。请踢我。

<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 个答案:

答案 0 :(得分: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处理程序中添加脚本 - 左侧面板中的第二个下拉列表