EN
HTML - select radio input on click on related text
3
points
In this article, we would like to show you how to select a radio input on click on the related text in HTML.
Quick solution:
// ONLINE-RUNNER:browser;
<input type="radio" name="field-name" value="some value ..." id="some-id" />
<label for="some-id" >Some label ...</label>
OR:
// ONLINE-RUNNER:browser;
<label>
<input type="radio" name="field-name" value="some value ..." />
<span>Some label ...</span>
</label>
Practical examples
1. Using input and label elements with id-for relation
In this example, we use input and label elements with id-for relation to enable radio input selection on the related text click (label text).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<input type="radio" name="group-name" value="value-1" id="one" checked />
<label for="one" >Value 1</label>
<br />
<input type="radio" name="group-name" value="value-2" id="two" />
<label for="two" >Value 2</label>
</body>
</html>
Note:
If the text inside the
labelelement wasn't bound by anid-forrelation, then the text could not be clicked.
2. Wrapping input with label element
In this example, we present how to enable radio input selection when you click the related text by wrapping the input and span elements with the label. This solution doesn't need the id and for attributes to specify the relation.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<label>
<input type="radio" name="group-name" value="value-1" checked />
<span>Value 1</span>
</label>
<br />
<label>
<input type="radio" name="group-name" value="value-2" />
<span>Value 2</span>
</label>
</body>
</html>
Note: by putting the text (e.g
<span>Value 1</span>) outside thelabelelement, you won't be able to click the related text anymore.