Search code examples
htmlradio-buttonrequired

HTML5: How to use the “required” attribute with a radio button with image?


Say I have some options presented to a user. The user can only select one option, hence the use of radio buttons. Instead of displaying boring radio buttons to the user, images are presented and when clicked, select a radio button.

The radio buttons are hidden and this is causing the problem with the required attribute.

Because the radio buttons are hidden, the required attribute is displayed for a moment and then disappears. If I make the radio buttons visible, everything works as intended.

Here is my markup:

<div class="form-group travelmodes">
    <label for="car"  style="border: 1px solid; background-image: url(/transportation-icons-06.png?width=200&amp;crop=0,0,200,200);">
        <span>Car</span>
        <input id="car" name="TravelMode" required type="radio" value="af60da7e-e0f6-438f-b633-a64e00b9a720">
    </label>
    <label for="aeroplane" style="border: 1px solid; background-image: url(/transportation-icons-09.png?width=200&amp;crop=0,0,200,200);">
        <span>Aeroplane</span>
        <input id="aeroplane" name="TravelMode" required type="radio" value="5fb4cb1e-6de2-4eb4-acf6-a64e00b9a721">
    </label>
</div>

If the above is not clear, please see this JSBin: Demo

How can I fix this so that I can have images, rather than visible radio buttons, and still use the required attribute?


Solution

  • Setting display: none causes the "required" popup to be hidden.

    Instead, you could try absolute positioning with a minuscule zoom:

    #invisible input[type="radio"] {
      position: absolute;
      zoom: 0.1;
    }
    

    JSBin