Search code examples
htmlradio-buttonlabel

How to prevent radio buttons being selected by clicking their labels


I have a group of radio buttons which each have their own labels. The label width is set to auto, which is what I want because the text length could increase in the future.

At the moment if I click the label it will select the corresponding radio button. As I understand it, this is default HTML behaviour. Is there any simple (by simple I mean preferably without using Javascript) way to suppress this default behaviour? So that I can select the radio button only by clicking the grey circle itself?

Radio button wrapped in Label


Solution

  • In order to change this behavior, you first need to understand how to associate checkbox/radio elements with a <label>. If you understand that, then you can ensure that the <input> element isn't associated with a <label> element in order to prevent it from being selected.

    There are two main ways:

    • Wrap the <input> element with a <label> element in order to implicitly associate the elements:

    <p>Wrapping the input elements with a label will cause the input element to be selected when clicking on the label.</p>
    
    <label>
        <input type="radio" name="confirm" />Initial Decision
    </label>
    <label>
        <input type="radio" name="confirm" />Confirmation
    </label>

    • Associate the <input> element's id with the <label> element's for attribute to explicitly associate the elements:

    <p>If the input element's id matches the label element's for attribute, then clicking on a label element will select the corresponding input element:</p>
    
    <input type="radio" id="initial" name="confirm" />
    <label for="initial">Initial Decision</label>
    
    <input type="radio" id="confirm" name="confirm" />
    <label for="confirm">Confirmation</label>

    Thus, you can effectively prevent the radio element from being selected when clicking on the <label> element by simply not associating the elements:

    <input type="radio" name="confirm" />
    <label>Initial Decision</label>
    
    <input type="radio" name="confirm" />
    <label>Confirmation</label>