0

I want to use javascript in a razor view in the MVC project. I want to show a message to the user by clicking the post button. I put the script tag in Section below the page but on hitting F12 it shows 'btn' is null. I'm testing my project on IISExpress in Firefox

<form method="post">
--------a few input fields in a form-------
 <button id="button" type="submit" class="btn btn-lg btn-success">send</button>
</form>
<div class="submit-progress d-none">
    <label>be patient please...</label>
</div>
@section scripts{
    <partial name="_ValidationScriptsPartial" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.2.7/js/fileinput.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            const btn = document.getElementById("#button");
            btn.addEventListener("click", function () {
                $(btn).prop("disabled", true);
                $(".submit-progress").removeClass("d-none");
            })
        });
    </script>
}

2 Answers 2

2

There are multiple problems with your code mostly from mixing jQuery and native JavaScript methods. You can make it work by fixing the 3 lines shown to use jQuery. Note that "this" refers to the element to which the event handler is attached, in this case the button.

$(document).ready(function() {
  // const btn = document.getElementById("#button"); <-- REMOVE
  $("#button").click(function() { // <-- CHANGE
    $(this).prop("disabled", true); // <-- CHANGE
    $(".submit-progress").removeClass("d-none");
  })
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Man! Could you please help me with another issue? In my form, I have a client-side validation which means If you hit send button without filling the form, validation tag errors appear without sending to the server. The problem is with appearing .submit-progress div. I want it to appear only when the user fills the form and hits the send button
2

When using getElementById you only need to pass the name not the selector #

const btn = document.getElementById("button");

You have used the scripts section correctly.

1 Comment

up voted as this is the most simple answer, though I think OP also needs to understand that they are mixing jQuery and native js in a confusing code salad.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.