How do you make the radio button text to be clickable too?
Asked Answered
L

4

66

I have this radio button (and some other after this one):

<input type="radio" name="group1" value="Milk"> Milk<br>

But if I want to activate the radio button, I have to click it, clicking the word "Milk" which is to the right of the button, doesn't activate it. How can I do that?, all the examples I found about radio buttons so far, have the same issue.

Liquidize answered 16/10, 2013 at 19:36 Comment(2)
possible duplicate of Radio Groups with clickable labelUnmeaning
possible duplicate of How to associate labels with radio buttonsRuano
N
144

Here you want to use the label tag.

Something like:

            <label>
                <input type="radio" name="group1" value="Milk">
                Milk
            </label><br/>

Labels tell the browser that everything contained within should be treated as one element (in terms of text. They are not divs)

Take a look at this for an example: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_label

Newsprint answered 16/10, 2013 at 19:38 Comment(2)
This works; however, the link shows an example like @Ruano answered.Imamate
So easy! and it greatly improves the usability of a site & makes it easier on mobile.Aviv
R
49

If you use the label tag, giving your radio button an ID, you should be able to click on the label to select the radio.

<input type="radio" name="group1" value="Milk" id="rad1">
<label for="rad1">Milk</label>

http://jsfiddle.net/tvFgU/1/

This is valid for xhtml 1.0 strict:

enter image description here

Ruano answered 16/10, 2013 at 19:39 Comment(1)
I see, is the "for" attribute valid in strict xhtml 1.0?Liquidize
K
8

For React JSX

<input type="radio" name="group" value="happy" id="rad1">
<label htmlFor="rad1">YES</label>

<input type="radio" name="group" value="sad" id="rad2">
<label htmlFor="rad2">NO</label>

Here Name attribute would be the same for both radio button.

Kohn answered 7/2, 2019 at 12:37 Comment(0)
M
1

Just an addition to the accepted answer. If your radio button is an item inside a list. in order to offer the best UX you should select the radio button even if the user clicks on the empty area in front of it.

To do so, inside your CSS file, set display: block for your label, same as the example below. This will force your label to fill the whole available area.

HTML file:

<li><label><input type="radio" value="eng">English</label></li>

CSS file:

label {
    display: block;
}

Doing so, user can click on the empty area in front of your text and the radiobutton would still be selected.

Mccready answered 23/4, 2023 at 17:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.