Reputation: 153
I have a series of radiobuttons in asp.net MVC and I want the whole text associated with the radiobutton to be clickable.
I have tried different variations but this is what I have currently.
@foreach (var process in Model.ProcessSelectionOptions)
{
@Html.RadioButtonFor(x => x.ProcessSelected, process.ID, new { id = "ProcessSelection", @title = process.Label })
@Html.Label(process.ID.ToString(), " " + process.Label, new { @title = process.Label, @for = process.ID })
}
Here is the output in html
<div class="checkbox">
<input data-val="true" data-val-number="The field ProcessSelected must be a number." data-val-required="*Process selection is required" id="ProcessSelection" name="ProcessSelected" title="User Affirmation Statement" type="radio" value="1" />
<label for="1" title="User Affirmation Statement"> User Affirmation Statement</label>
<input id="ProcessSelection" name="ProcessSelected" title="Annual Data Security Recertification" type="radio" value="2" />
<label for="2" title="Annual Data Security Recertification"> Annual Data Security Recertification</label>
</div>
I have seen some examples online about wrapping the label around each radiobutton for but they are all hardcoded values. Is there a way to accomplish this?
Upvotes: 1
Views: 3766
Reputation: 622
The html way to associate labels with inputs, is configuring the "for" attribute of the label with the id of the input it should be associated with.
The problem you have here is that you have the same id for all inputs, which also violates the html specification. You should give each input a different id, and use that id in the "for" attribute of the associated label. Brian Warshaw's answer addresses this issue. Havent tried it but looks okay.
Also if that radio buttons should work together as a group (only one of them should be selected) all of them should share the same "name" attribute. Try if this works:
@foreach (var process in Model.ProcessSelectionOptions)
{
@Html.RadioButtonFor(x => x.ProcessSelected, process.ID, new { id = "ProcessSelection" + process.ID.ToString(), @title = process.Label, @name = "myRadioGroup" })
@Html.Label(process.ID.ToString(), " " + process.Label, new { @title = process.Label, @for = "ProcessSelection" + process.ID.ToString() })
}
Upvotes: 2
Reputation: 22984
Try this:
@foreach (var process in Model.ProcessSelectionOptions)
{
@Html.RadioButtonFor(x => x.ProcessSelected, process.ID, new { id = "ProcessSelection" + process.ID.ToString(), @title = process.Label })
@Html.Label(process.ID.ToString(), " " + process.Label, new { @title = process.Label, @for = "ProcessSelection" + process.ID.ToString() })
}
Upvotes: 2
Reputation: 1125
I had the same poblem but instead of radiobuttons i used checkboxes. To do the trick i putted each element inside of a <div class="form-group"> .. </div>
, but i used bootstrap plugin to do that. Let me know if it works as well
Upvotes: 1