Select an HTML radio button by clicking on its text
This post will discuss how to select an HTML radio button by clicking on its text.
The idea is to associate an HTML <label> element with its corresponding radio button. We can do this by providing the radio’s ID attribute value in the for attribute of the <label> element. Now, you can click the associated label to select the corresponding radio button.
The following example demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <input type="radio" id="java" name="language" value="java"> <label for="java">Java</label> <input type="radio" id="cpp" name="language" value="cpp"> <label for="cpp">C++</label> <input type="radio" id="python" name="language" value="python"> <label for="python">Python</label> </div> <button id="submit">Submit</button> </div> </body> </html> |
If your radio button doesn’t have an id attribute, you can wrap the radio button directly inside the <label> element. Now, for and id attributes are not required since the association is implicit.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<html> <body> <div id="container"> <p>Select your favorite programming language:</p> <div> <label><input type="radio" name="language" value="java">Java</label> <label><input type="radio" name="language" value="cpp">C++</label> <label><input type="radio" name="language" value="python">Python</label> </div> <button id="submit">Submit</button> </div> </body> </html> |
That’s all about selecting an HTML radio button by clicking on its text.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)