首页 > 解决方案 > Html.CheckBoxFor 使用 Jquery 查找状态

问题描述

我在尝试获取复选框的状态时遇到了一些问题。它是一个@Html.CheckBocFor带有 id 的。出于某种原因,我无法获取此代码来检查它的状态。这是在一个$("form").submit函数中。我基本上是在检查是否满足必填字段。以下是我尝试过的事情:

 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");
    }

 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");
    }

我在控制台窗口中也没有收到任何错误。就像它不读取复选框一样。这是我的复选框

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

产生这个:

<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" />

data-val-required我对我的模型中没有任何代码表示这是必填字段感到有些困惑。我还多次清除了所有浏览数据。

任何帮助将不胜感激。

更新:

我发现控制台窗口中出现了一个错误,它无法获取 null 的值。所以我查看了更多复选框,发现这在放置 a 时确实有效,console.log(cb.checked)并且它写入控制台窗口。所以它现在读取它是错误的,但不会填充警报。自定义警报。这是我的新代码。

    const cb = document.getElementById('AcceptTerms');
    //console.log(cb.checked);
    if (cb.checked == false) {
        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");
    }

它确实将其读取为错误,但无法启动 showAlert。这个有效

 if ($("#SignatureDataUrl").val().trim() == "") {
        e.preventDefault();
        showAlert("<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");
    }

它更像是一个函数。而另一个不是。有没有办法将其格式化为函数类型?

更新:这仅在我debugger;未注释时才有效。它显示警报,但是当我继续时它消失并出现下一个警报。

 if ($(!'#AcceptTerms:checked')) {
        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");
        //debugger;
    }

更新:

对这个真的很茫然。它似乎只有在我debugger;取消注释时才会弹出。它正在通过代码,因为它在cb.checked未选中复选框时正在登录控制台窗口。下面是我的自定义警报和表单提交警报的完整代码,除了#AcceptTerm我没有显示警报之外,所有这些都可以工作debugger;

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

var myAlert = new bootstrap.Modal(document.getElementById('myAlert'))

function showAlert(msg, type) {
    document.getElementById("alertContent").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>`
    myAlert.show()
    //debugger;
}

$("form").submit(function (e) {
    const cb = document.getElementById('AcceptTerms');
    if (cb.checked == false) {
        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");
        console.log(cb.checked)
        //debugger;
    }

    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");
        //debugger;
    }

    if ($("#SignatureDataUrl").val().trim() == "") {
        e.preventDefault();
        showAlert("<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");
    }

    //showConfirm = false;
});

更新:按照我给出的两个例子,他们都做同样的事情。弹出的另一个警报仍然存在问题,现在显示所有未给出的警报,这不应该因为它不是提交而是文本框点击。见下文,也许是导致它像提交一样的行为,不确定。喜欢一个按钮,如果不是类型按钮将提交。

    $(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");
    });
  
});

并回答洛朗。我明白你所说的验证是什么意思。这是一个签名板。我正在处理填写此内容的患者。我只是想让他们清楚他们需要做什么来确保他们需要做什么。捕获他们的签名并将其应用于完成的 Pdf 的简单表格。完成后,信息将被删除。

更新:我使用了 Laurent 的例子。它可以工作并解决非表单提交警报的问题,我刚刚为它添加了一个新容器。所以这是完成的代码..

 <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>

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 +
   /* document.getElementById("alertContent").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>`
    //myAlert.show()
    //debugger;
}

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()
    //debugger;
}

$(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 = "";
    //document.getElementById("alertContent").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)
        //debugger;
    }

    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");
        //debugger;
    }

    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();
    //showConfirm = false;
});

感谢大家的帮助。

标签: javascriptc#jqueryasp.net-mvc

解决方案


您似乎只是在重复替换错误消息显示区域的内容:<div>带有id=AlertContent.

您想显示可能的消息 A、B 和 C。而不是将这三个消息写在同一个显示区域上,例如 A B C

你写A,然后擦掉它,写B,然后擦掉它,写C。所以你只看到C。

当您添加debugger;一行时,您会看到新放置的内容,然后它会被删除并被新内容替换。但是当您删除它时,内容会立即被新内容替换,因此您的问题。

如果您想查看所有可能的消息,则每条消息不应替换前一条,而应添加到消息列表中。

由于您正在显示模式,您应该首先获取所有要显示的消息,将它们添加到您的显示元素,最后显示您的模式。

但我认为使用 Modal 进行表单验证并不是一个好主意。您可能应该查看客户端表单验证最佳实践,并查看您尝试实现的目标是否还不受库(如 jquery-validate)的支持。

只是为了让您大致了解什么可以纠正您的代码:(未测试)。我不会亲自使用它。

模态 HTML

<div id="myAlert" class="modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <div id="alertContent">
        <!-- Your messages will appear here -->
        </div>
      </div>
    </div>
  </div>
</div>

部分 Javascript 代码:

var myAlert = new bootstrap.Modal(document.getElementById('myAlert'))

var errorMessageDisplayArea = document.getElementById("alertContent");

function addMessage(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>`
}


$("form").submit(function (e) {
    // Clear the Modal content.
    errorMessageDisplayArea.innerHTML = "";
    
    const cb = document.getElementById('AcceptTerms');
    if (cb.checked == false) {
        e.preventDefault();
        $("#AcceptTerms").focus();
        addMessage("<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)
        //debugger;
    }

    if ($("#TypedName").val().trim() == "") {
        e.preventDefault();
        $("#TypedName").focus();
        addMessage("<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");
        //debugger;
    }

    if ($("#SignatureDataUrl").val().trim() == "") {
        e.preventDefault();
        addMessage("<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();
    //showConfirm = false;
});

推荐阅读