CSS HTML

How to select a radio by clicking on the text next to it?

March 12, 2022

How to select a radio by clicking on the text next to it?

In this article we will learn how to select a radio by clicking on the text next to it, so that the user does not need to click only on the radio button input.

select a radio by clicking on the text next to it thumb

What’s up programmer, how are you? Let’s learn something new!

We can solve the problem of clicking on text and selecting radio input with just HTML

Which is very good, because sometimes we are puzzled by crazy solutions or even start with a JavaScript approach.

The technique consists of just adding a label with the text that is next to the radio, which points to the id of the input

In this way, the text ‘becomes’ part of the input, allowing you to click on it as well.

Let’s take a practical example:

<h1>Select your preferred car brand</h1>
<form>
 <input type="radio" name="cars" id="bmw"><label for="bmw">BMW</label>
 <input type="radio" name="cars" id="audi"><label for="audi">Audi</label>
 <input type="radio" name="cars" id="jac"><label for="jac">JAC</label>
</form>

Above we have a basic HTML, of a form that has the radio inputs

And we use the label technique, with for attribute is pointing to the radio id

Note that if you add the wrong id in the other labels, they may not work.

And even if you add an id from another radio, it will select that other one and not the closest one

You need to do the same as the example and insert the corresponding id

See what is represented in the browser:

Doing that way, our problem is solved!

Conclusion

In this article we learned how to select a radio by clicking on the text next to it

The idea is very simple, we just add a label with a for attribute that must match the id of the radio input

From there, clicking on the text we will automatically select the radio

Which will give greater usability to the customer/person who accesses the site

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x