In my view, I want two buttons to populate three hidden fields of a form and submit it. It's not working, and I can't know why. Any ideas?
I have the following code:
<script language="javascript" type="text/javascript">
function FillAndSubmit(thisid) {
$('input[name=First]').val(thisid);
$('input[name=Second]').val(@Model.ID);
$('input[name=Third]').val(@ViewBag.Something);
document.form.submit();
}
</script>
A have a form with invisible fields:
@using (Html.BeginForm(null, null, FormMethod.Post,
new { name = "form", id = "form" }))
{
@Html.Hidden("First")
@Html.Hidden("Second")
@Html.Hidden("Third")
}
And two buttons:
<button class="Button" id="ButtonA" onclick="javascript:FillAndSubmit(this.id);">
CaptionA
</button>
<button class="Button" id="ButtonB" onclick="javascript:FillAndSubmit(this.id);">
CaptionB
</button>
If I put the buttons inside the scope of the form, it submits but without populating the hidden fields. So, it is just not calling the function. Javascript is working in other pages of the same application.
ADDED:
Generated source:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Title</title>
<link href="/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function Botao(thisid) {
$('input[name=First]').val(thisid);
$('input[name=Second]').val(41);
$('input[name=Third]').val(10/5/2012 1:58:02 PM);
document.form.submit();
}
</script>
...
Some div's with some text
...
<form action="/Controller/Action/" id="form" method="post" name="form"><input id="First" name="First" type="hidden" value="" /><input data-val="true" data-val-required="The DateTime field is required." id="Second" name="Second" type="hidden" value="10/5/2012 1:58:02 PM" /><input id="Third" name="Third" type="hidden" value="" /></form>
<button class="Button" id="ButtonA" onclick="javascript:Botao(this.id);">
CaptionA
</button>
<button class="myButton" id="ButtonB" onclick="javascript:Botao(this.id);">
CaptionB
</button>
</body>
</html>
javascript:part of youronclickattributes since is not needed?. Have you tried to debug with aconsole.logto see if the function is called?. Have you tried to call the function directly from the Browser's JS console?javascript:didn't do anything. I will check the JS console now.Model.IDis a number, andViewBag.Somethingis aDateTime.