VS2013, MVC5, VB, in a Razor View
I wanted to set the value for a string that will be posted back to the controller. I'm pretty new to javascript, but I found this (link) which included the following code:
<input type="text" id="mytext">
<script type="text/javascript">
var elem = document.getElementById("mytext");
elem.value = "My default value";
</script>
When I try to type that in, the 'value' property as seen on 'elem' above is not available. Why would that be?
Ultimately I am trying to modify a form field that will be returned to a controller. While my question above is what I'm wondering about, I thought it would be useful to include the full context.
The view is setup with:
@Using (Html.BeginForm(Nothing, Nothing, FormMethod.Post, New With {.id = "thisForm"}))
My input element is:
<input type="button" onclick="UserCommit()" value="Next" class="btn btn-default" tabindex="2" />
And the script shell is:
<script type="text/javascript">
function UserCommit() {
$("#thisForm").submit()
}
</script>
The script above works and submits the form the same as the original input element which was:
<input type="submit" value="Next" class="btn btn-default" tabindex="2" />
I wanted to combine the value of multiple checkbox fields together into the single form field the controller is expecting back, so I figure I could use javascript to concatenate all the checked fields into the expect field. But I don't seem to be able to access the form field as the SO post that I linked to above suggests.
My current view uses html helpers and generates the follow html (this was taken looking at the generated source):
<input id="Response1" name="Response1" type="checkbox" value="true" /><input name="Response1" type="hidden" value="false" /> one<br />
<input id="Response2" name="Response2" type="checkbox" value="true" /><input name="Response2" type="hidden" value="false" /> two<br />
The actual form element expected is "Response", so if I concatenate Response1 and Response2 and so on, the Response will capture the data of however many checkboxes were created and checked. The controller is expecting to see "Response" and it is a bound field in the receiving method.
This is what I typed in:
<script type="text/javascript">
function UserCommit() {
var myElement = document.getElementById("Response");
myElement.value = "A new response";
$("#thisForm").submit()
}
</script>
But, the '.value' seen above doesn't show up in Intellisense, and of course doesn't run.
Added after original post:
I did also find this (link) SO post for using the checkbox helper which I will study and try to follow. But the javascript question still remains.
added for mplungjan in comments. Is this what you are asking, the line that generates the "Response" field?
@Html.CheckBox("Response", False)
That line in turn generates:
<input id="Response" name="Response" type="checkbox" value="true" /><input name="Response" type="hidden" value="false" />