You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery获取@Html.CheckBoxFor选中状态时自定义告警异常排查

解决jQuery读取@Html.CheckBoxFor生成复选框状态及告警冲突问题

问题背景

开发过程中在$("form").submit提交事件中校验表单必填项时,读取id为AcceptTerms的复选框状态出现异常:未勾选时可正常阻止表单提交,但自定义告警无法弹出,控制台也无报错,而同函数内针对TypedName输入框的空值校验逻辑可正常触发告警。

初始尝试的错误代码

// 原生JS读取复选框状态逻辑
if (!document.getElementById("AcceptTerms").checked) {
    e.preventDefault();
    $("#AcceptTerms").focus();
    showAlert.Alert("You must accept terms and conditions in order to proceed to the next step.", "error");
}

// jQuery读取复选框状态逻辑
var AcceptTerms = $("#AcceptTerms").is(":checked");
if (AcceptTerms) {
} else {
    e.preventDefault();
    $("#AcceptTerms").focus();
    showAlert("<i class='bi-exclamation-octagon-fill' style='font-size:20px;'></i>&nbsp;You must accept terms and conditions in order to proceed to the next step.", "danger");
}

同函数内可正常运行的输入框校验代码:

if ($("#TypedName").val().trim() == "") {
    e.preventDefault();
    $("#TypedName").focus();
    showAlert("<i class='bi-exclamation-octagon-fill' style='font-size:20px;'></i>&nbsp;You must type your name in order to proceed to the next step.", "danger");
}

相关基础代码

Razor复选框代码

@Html.CheckBoxFor(model => model.AcceptTerms, new { @id = "AcceptTerms" })

生成的DOM结构

<input data-val="true" data-val-required="The AcceptTerms field is required." id="AcceptTerms" name="AcceptTerms" type="checkbox" value="true" /><input name="AcceptTerms" type="hidden" value="false" />

生成的DOM自动携带了模型中未配置的data-val-required必填属性,多次清理浏览器缓存该属性仍存在。

调试过程异常现象

  • 控制台闪过null值读取报错,调整代码后可通过console.log(cb.checked)打印到未勾选状态的false值,但仍无法触发showAlert告警
  • 仅取消debugger;语句注释时告警会短暂弹出,代码继续执行后立即消失
  • 点击TypedName文本框触发的非提交类告警和表单提交告警共用容器,出现内容冲突问题

最终解决方案

核心思路:拆分两个Bootstrap Modal告警容器,分别封装showAlert和showMessage方法隔离不同场景的告警内容。

完整实现代码

告警容器HTML

<div id="myAlert" class="modal" tabindex="-1">
    <div id="alertContent" class="modal-dialog"></div>
</div>
<div id="myAlert2" class="modal" tabindex="-1">
    <div id="alertContent2" class="modal-dialog"></div>
</div>

交互逻辑JS

var myAlert = new bootstrap.Modal(document.getElementById('myAlert'))
var myAlert2 = new bootstrap.Modal(document.getElementById('myAlert2'))
var errorMessageDisplayArea = document.getElementById("alertContent");

// 表单提交校验告警方法
function showMessage(msg, type) {
    var previousContent = errorMessageDisplayArea.innerHTML;
    errorMessageDisplayArea.innerHTML = previousContent +
    `
  <div class="alert alert-${type} alert-dismissible d-flex align-items-center fade show" role="alert">
    <button id="myBtn" type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        ${msg}
  </div>`
}

// 非提交场景交互告警方法
function showAlert(msg, type) {
    document.getElementById("alertContent2").innerHTML = `
      <div class="alert alert-${type} alert-dismissible d-flex align-items-center fade show" role="alert">       
        <button id="myBtn" type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            ${msg}
      </div>`
    myAlert2.show()
}

// TypedName点击提示逻辑
$(document).on("click", "#TypedName", function () {     
    showAlert("<i class='bi-exclamation-triangle-fill' style='font-size:20px;'></i>&nbsp; By typing your name in the signature box, you are certifying that you are the authorized Adult or Guardian who completed the new patient packet and the information provided is accurate to the best of your knowledge.", "warning");
    $("#TypedName").focus();
    $("#myAlert").fadeTo(2000, 500).slideUp(700, function () {
        $("#myAlert").slideUp(500);
        $("body").removeClass("modal-open");
        $("div").removeClass("modal-backdrop show");
    });
});

// 表单提交校验逻辑
$("form").submit(function (e) {
    errorMessageDisplayArea.innerHTML = "";
    const cb = document.getElementById('AcceptTerms');
    if (cb.checked == false) {
        e.preventDefault();
        $("#AcceptTerms").focus();
        showMessage("<i class='bi-exclamation-octagon-fill' style='font-size:20px;'></i>&nbsp;You must accept terms and conditions in order to proceed to the next step.", "danger");
        console.log(cb.checked)
    }

    if ($("#TypedName").val().trim() == "") {
        e.preventDefault();
        $("#TypedName").focus();
        showMessage("<i class='bi-exclamation-octagon-fill' style='font-size:20px;'></i>&nbsp;You must type your name in order to proceed to the next step.", "danger");
    }

    if ($("#SignatureDataUrl").val().trim() == "") {
        e.preventDefault();
        showMessage("<i class='bi-exclamation-octagon-fill' style='font-size:20px;'></i>&nbsp;You must draw your name in the box provided and Press Accept in order to proceed to the next step.", "danger");
    }

    myAlert.show();
});

内容的提问来源于stack exchange,提问作者S.Purtan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:24:03