Chris Wignall Chris Wignall - 3 months ago 14
HTML Question

How can I make a button clickable within a radio button?

I understand that I can make clickable text next to a radio a button, so that clicking the text toggles the radio button.

<label>
Click me
<input type="radio" value="selected"><br>
</label>


I want to have a button as my label, but when I do this the radio button is not toggled when I click the button.

<label>
<button type="button">Click</button>
<input type="radio" value="selected"><br>
</label>


How can make the button label toggle the radio button when clicked?

I want to do this as I have some code which uses buttons containing styled images, and I want to change it to use radio buttons underneath and keep the existing buttons.

Answer

You can use CSS' pointer-events to make mouse events "fall through" the button and onto the label:

button
{
    pointer-events: none;
}
<label for="target">
    <button type="button">Click</button>
    <input id="target" type="radio" value="selected"><br>
</label>

Note that you'll also have to set the for attribute of the label for it to work correctly, if it contains more than one human input element.

Also note that this makes the button entirely inaccessible, so any event handlers will not be triggered anymore (but it seems that this is what you want).

Comments