1

I have an Index.cshtml in a C# application. This is the code of the form:

 @using (Html.BeginForm("CheckPlanID", "ForgotUserID", FormMethod.Post)) { <section class="vh-100" style="background-color: #508bfc;"> <div class="container py-5 h-100"> <div class="row d-flex justify-content-center align-items-center h-100"> <div class="col-12 col-md-8 col-lg-6 col-xl-5"> <div class="card shadow-2-strong" style="border-radius: 1rem;"> <div class="card-body p-5 text-center"> <h3 class="mb-5">Forgot User ID</h3> <div class="form-outline mb-4"> <label id="errorLabel" name="errorLabel" class="form-label @Model.GeneralErrorColor">@Model.GeneralError</label> </div> <div class="form-outline mb-4"> <input type="text" id="PlanID" asp-for="PlanID" name="PlanID" class="form-control form-control-lg" value="@Model.PlanID" /> <label class="form-label @Model.ErrorPlanIDColor" for="PlanID">@Model.ErrorPlanID</label> </div> <button class="btn btn-primary btn-lg btn-block" type="submit" id="nextButton" onclick="DisplayProgressMessage(this, 'Login');">Next</button> </div> </div> </div> </div> </div> </section> <div class="submit-progress hidden" style="background-color: #3b5998; text-align: center;"> <i class="fa fa-2x fa-refresh fa-spin" style="color: white"></i> <label style="color: white">Please wait...&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label> </div> } 

When the user clicks on the Next button, I execute the following jQuery:

 <script> function DisplayProgressMessage(ctl, msg) { var planID = $("#PlanID").val(); console.log("plan ID = " + planID); console.log("length = " + planID.length); if (planID.length == 4) { $(ctl).prop("disabled", true).text(msg); $("#nextButton").prop("disabled", true); // Wrap in setTimeout so the UI // can update the spinners setTimeout(function () { $(".submit-progress").removeClass("hidden"); }, 1); $("form").submit() } $("#errorLabel").text = "The Plan ID must be 4 characters in length"; } </script> 

When I run the application and type in 4 characters into the input box and click on the Next button, the jQuery executes, the hidden gets displayed, and the form gets submitted to my controller. This is correct.

When I run the application and type in 2 characters into the input box and click on the Next button, the jQuery executes, the hidden <div< does not get displayed, but the form still gets submitted to my controller.

How can I get jQuery to not submit the form when the length of the data typed into the input box is not 4?

Thank you

    1 Answer 1

    1

    Since your button has a type of "submit" it will always submit the parent form, unless you prevented the events default behavior.

    The easiest solution is to change your button to type = "button".

    1
    • 1
      gotta love easy. Thank you very much!CommentedSep 16, 2022 at 20:05

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.