Example;
<%=Html.RadioButton("MyRadioButton","MyValue")%>renders
<input id="MyRadioButton" value="MyValue" name="MyRadioButton" type="radio">To get the label we just add the label tag and uses the input tags id as reference for the label.
<label for="MyRadioButton">My description</label>This will allow us to check the radio button by clicking on the label as well.
Then the problem occurs if we should use multiple radio buttons with the same name.
Example;
<%=Html.RadioButton("IsItRaining","Yes")%>This will render
<%=Html.RadioButton("IsItRaining","No")%>
renders
<input id="IsItRaining" value="Yes" name="IsItRaining" type="radio">
<input id="IsItRaining" value="No" name="IsItRaining" type="radio">
This it not so well since we need different id attributes to be able to bind the label tags.
To fix this we need to add different ids to the input tags.
Example:
<%=Html.RadioButton("IsItRaining", "Yes", new {id="IsItRaining_Yes"})%><label for="IsItRaining_Yes">Yes</label>That will produce the intended output;
<%=Html.RadioButton("IsItRaining", "No", new {id="IsItRaining_No"})%><label for="IsItRaining_No">No</label>
<input id="IsItRaining_Yes" type="radio" value="Yes" name="IsItRaining"/>And will work as below
<label for="IsItRaining_Yes">Yes</label>
<input id="IsItRaining_No" type="radio" value="No" name="IsItRaining"/>
<label for="IsItRaining_No">No</label>
Thanks for sharing this. Very helpful!
ReplyDeleteOr you could do it the lazy way and just wrap the entire thing in a [label] tag.
ReplyDelete