Reputation: 81573
This is an easy question for those in know, however, with a Google Search and Stack search i found there was no direct or straight answer.
I have a simple CheckBoxFor
@Html.CheckBoxFor(x => x.Classify)
which is generating the following 2 page elements
<input data-val="true" data-val-required="The Classify field is required." id="Classify" name="Classify" onclick="OnClassifyClick(this)" type="checkbox" value="true" data-bind="checked:Classify">
<input name="Classify" type="hidden" value="false" data-bind="value:Classify">
Obviously the second element is used for binding <-- this assumption is incorrect
How can i use jquery to change both of these values, so the posted model will reflect the state
The following code only changes the visual state and not the bound state (if that's the correct terminology) <-- this assumption is incorrect
$("#Classify").attr('checked', true);
results in the following
<input data-val="true" data-val-required="The Classify field is required." id="Classify" name="Classify" onclick="OnClassifyClick(this)" type="checkbox" value="true" data-bind="checked:Classify" checked="checked">
<input name="Classify" type="hidden" value="false" data-bind="value:Classify">
As you can see the bound value hasn't changed
Update
The example should work, see the excepted answer
Upvotes: 1
Views: 2447
Reputation: 897
This code will change the checked status of checkbox to false if true.
if ($("#cbinPro").is(":checked")) {
$("#cbinPro").click();
}
Upvotes: 1
Reputation:
Obviously the second element is used for binding
This is not strictly correct. The reason the @Html.CheckBoxFor()
method renders both a checkbox and a hidden input is that unchecked checkboxes not not post back a value. If the checkbox is not checked, then the hidden inputs 'false' value is posted back. If the checkbox is checked, then its 'true' value is posted back and hidden inputs value is ignored (the default model binder ignores subsequent values with the same name).
You can see the source code here.
Therefore you should not need to change the value of the hidden input, and doing so would probably result in posting back an incorrect value.
Upvotes: 1