Thomas Thomas - 1 year ago 83
Javascript Question

Programmatic Form POST from jQuery doesnt work in document ready

I have the below script in my code:

<script src="~/Scripts/jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready()
{
$("#hdnTest").text('@ViewBag.Test');
$("#frmRouter").submit();
};

function submitform()
{
$("#frmRouter").submit();
}
</script>


I also have the below html in my mvc view:

<form id="frmRouter" method="post" action="https://localhost/Destination/Index">
<div>
<input type="hidden" id="hdnTest" name="hdnTestName" />
</div>
<a href="#null" onclick="submitform();">Click</a>
</form>


When I click on the hyper link, the form is getting posted to the action URL. However, the form submit inside the document.ready doesn't work. Why is it so?

Answer Source

Your document.ready has not the correct syntax. You have two ways to perform a document.ready function.

$(document).ready(function () {
    $("#hdnTest").text('@ViewBag.Test');
    $("#frmRouter").submit();
});

$(function () {
    $("#hdnTest").text('@ViewBag.Test');
    $("#frmRouter").submit();
});