验证消息过早触发

时间:2013-07-20 11:17:32

标签: jquery validation checkbox

我有以下代码,我想要它,如果我取消选中该复选框,它将显示验证消息。

我的代码

的jQuery

if($('#TermsAndConditions').is(':checked')) 
{
} else {
    alert('Not checked);
}

查看

<div class="editor-field">
    <%:Html.CheckBox("TermsAndConditions")%> <%: Html.ActionLink("I agree Terms and Conditions", "Terms", "Home")%>
</div>

但是,每当我加载表单时,都会显示一条警告消息。你能帮我辨认一下这个问题吗?

4 个答案:

答案 0 :(得分:1)

这是因为您将脚本放置在页面顶部。基本上你的脚本是在作用域中存在#TermsAndCondition复选框之前加载的,因此它会使你的条件失败并触发else,并且它也不会被事件触发(例如表单提交或复选框状态更新)不希望的。

您应该在触发事件时执行操作,例如更改复选框状态时。

$("#TermsAndConditions").on("change", function(){
   if($(this).is(':checked')) 
   {
   } else {
       alert("Not checked");
   } 
});

或提交表单时

$("#YourFormId").on("submit", function(e){
   if($("#TermsAndConditions").is(':checked')) 
   {
       // Form will submit
   } else {
       // Form will not submit
       alert("Not checked");
       e.preventDefault();
   } 
});

See working demo here

答案 1 :(得分:0)

你把你的jquery代码放在哪里?页面完全加载后你确定它正在运行吗?您可能需要将它放在$(function(){ .. code .. });中,如下所示:

$(function(){
    if($('#TermsAndConditions').is(':checked')) {

    }
    else {
       alert('Not checked);
    }
});

或者像@Duk说绑定它来提交事件。

答案 2 :(得分:0)

$('#TermsAndConditions').on('change', function () {
    if (this.checked) {

    } else {
        alert('Not checked');

    }
});

或者您希望提交的任何其他处理程序,例如

DEMO

答案 3 :(得分:0)

由于在页面加载期间没有条件触发事件。使用change事件

 $(document).ready(function(){
    $('#TermsAndConditions').change(function(){
            if($(this).is(':checked')) {

            }
            else {
               alert('Not checked);
            }
        });
  });
相关问题