1

I have a modal that is prompted upon clicking the button 'submitBtn' (contained within the form), the one button in my modal (btnSubmit) should submit the form using javascript code. However, it fails to do so and throws an error;

" Uncaught TypeError: Cannot read property 'submit' of null at HTMLButtonElement. (Category:72)strong text "

i am unsure as to why its doing this? The alert runs as intended..

Below is my form, and below that is my script tag housing the necessary javascript code.. Any help would be greatly appreciated, thank you :)

Form HTML: (LINKED TO 'CategoryController')

@using (Html.BeginForm("Category", "Category", FormMethod.Post))
{

    <form id="formField">

        <label id="CategoryDescriptionLabel">Description</label>

        <input id="CategoryDescription" type="text" name="categoryDescription" /> 

        <input type="button" value="submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" /> 

    </form>

}

Javascript:

<script>

    document.getElementById("btnSubmit").addEventListener("click", function () {
        alert("Submitting!");
        document.getElementById("formField").submit()
    });

</script>

NB: Both code snippets are within the cshtml file..

1 Answer 1

1

You have in fact defined 2 nested forms: first one using Html.BeginForm() (this already wraps whatever is inside it between <form> and </form>) and then another one manually by using <form> and </form> tags.

Having nested forms is illegal in HTML. It is best to leave out the manually created <form>, change it to this:

@using (Html.BeginForm("Category", "Category", FormMethod.Post))
{
    <label id="CategoryDescriptionLabel">Description</label>

    <input id="CategoryDescription" type="text" name="categoryDescription" /> 

    <input type="button" value="submit" id="submitBtn" data-toggle="modal" data-target="#confirm-submit" /> 
}

To define an id for the generated <form>, you can use this:

@using (Html.BeginForm("Category", "Category", FormMethod.Post, new { id = "bla" }))
{
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

Oh okay, i see what you mean, how would i reference Html.BeginForm() in my javascript? Is it possible to assign an ID to this form?

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.