Home > Software design >  Html.CheckBoxFor using Jquery to find state
Html.CheckBoxFor using Jquery to find state

Time:11-14

I am having some issues trying to get the state of a checkbox. It is a @Html.CheckBocFor with an id. For some reason I cannot get this code to check the state of it. This is in a $("form").submit function. I am basically checking to see if the required fields are met. Here are the things I have tried:

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

There were a few others I tried as well and for some reason they are not showing the alert when not checked. The form will not submit, but no error either. I have other things in the function that do work Example below:

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

I do not get any error in the console window either. It like it doesn't read the checkbox. This is my checkbox

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

Which produces this:

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

I am a little confused at the data-val-required I do not have any code in my model that says this is a required field. I also have cleared all my browsing data several times.

Any help would be greatly appreciated.

UPDATE:

I found that there was a flash of error in console window that it could not get the value of null. So I looked up some more checkboxes and found that this does work while putting a console.log(cb.checked) and it writes to the console window. So it is now reading it false but will not populate the alert. The custom alert. Here is my new code.

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

It does read it as being false but fails to initiate the showAlert. This one works

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

it is more like a function. while the other is not. Is there a way to format that into a function type?

UPDATE: This works only if I have debugger; uncommented. It shows the alert, but when I continue it goes away and the next alert shows up.

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

UPDATE:

Really at a loss with this one. It seems to only popup when I have debugger; uncommented. It is going through the code because it is logging in the console window cb.checked when the checkbox is not checked. Below is the entire code for both my custom alert and the Form submit alerts, which all work except the #AcceptTerm will not show alert unless I have debugger; on.

<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 hljs-subst">${type} alert-dismissible d-flex align-items-center fade show" role="alert">       
    <button id="myBtn" type="button"  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;
});

UPDATE: Following the 2 examples I was given, they both do the same thing. There is still an issue with the other alert that pops up that now shows all the alerts that are not given, which shouldn't because it is not a submit but a textbox click. See below, Maybe it is the behavior that is causing it to act like a submit, not sure. Like a button if not type button will submit.

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

And to answer Laurent. I understand what you mean by validation. This is a signature Pad. I am dealing with Patients filling this out. I just wanted it to be clear to them what they need to make sure they need to do. Simple form that captures their signature and applies it to the finished Pdf. Once completed the information is deleted.

UPDATE: I used Laurent's example. It works and to fix the issue with the non form submit alert, I just added a new container for it. So here is the finished code..

 <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 hljs-subst">${type} alert-dismissible d-flex align-items-center fade show" role="alert">
    <button id="myBtn" type="button"  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 hljs-subst">${type} alert-dismissible d-flex align-items-center fade show" role="alert">       
        <button id="myBtn" type="button"  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;
});

Thanks for every ones help.

CodePudding user response:

It seems you are simply replacing repeatedly the content of your error message display area: the <div>element with id=AlertContent.

You want to show possibly messages A, B, and C. Instead of writing the three messages on the same display area, like A B C

You write A, then erase it and write B, then erase it and write C. So you see only C.

When you add a debugger; line, you see the newly placed content, before it gets erased and replaced by a new content. But when you remove it, the content is immediately replaced by a new one, hence your problem.

If you want to see all possible messages, each message should not replace the previous one, but be added at a list of message.

Since you are showing a modal, you should first get all the messages to be displayed, add them to your display element, and at the end show your modal.

But I don't think that using a Modal for form validation is a good idea. You should probably have a look at client side form validation best practices, and see if what you are trying to achieve is not already supported by a library, like jquery-validate.

Just to give you a rough idea of what could correct your code: (not tested). I would not personnaly use this.

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

Part of the javscript code:

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 hljs-subst">${type} alert-dismissible d-flex align-items-center fade show" role="alert">       
    <button id="myBtn" type="button"  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;
});
  • Related