Reputation: 55112
I have radio button as below for some reason even though the first one is checked, always the last one shows up checked on the form page. Why ? How can i fix this?
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Not, new { @checked = "true" })
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Maybe, new { @checked = "false" })
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Yes, new { @checked = "false" })
Upvotes: 2
Views: 9755
Reputation: 28157
The HTML specification says:
When any of the following phenomena occur, if the element's checkedness state is true after the occurrence, the checkedness state of all the other elements in the same radio button group must be set to false:
- The element's checkedness state is set to true (for whatever reason).
- The element's name attribute is set, changed, or removed.
- The element's form owner changes.
So as the HTML is parsed going down the page, if multiple radios are checked
then the last one will always be selected. As such, you only want to set one checked attribute by setting checked="checked"
:
@Html.RadioButtonFor(
model => model.IsSatisFied,
Satisfaction.Not,
new { @checked = "checked" })
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Maybe)
@Html.RadioButtonFor(model => model.IsSatisFied, Satisfaction.Yes)
Upvotes: 0
Reputation:
Do not set the checked
attribute. @checked = "true"
and @checked = "false"
(and checked
or checked="checked"
or checked="anything"
) all set the checked
attribute. As the DOM is read, the first one is checked, then the second, and finally the last one is checked.
If the value of propery is IsSatisFied
is Satisfaction.Maybe
then the second radio button will be selected (that's how model binding works)
Upvotes: 2
Reputation: 19526
You're using malformed HTML. The proper way to mark something as checked would be
{ @checked = "checked" }
and don't include the checked attribute at all for the unchecked radio buttons.
Upvotes: 0