How to make form labels work for images in IE and Safari Nov 8 2005

You already use <label> tags for your forms, right? This is the great little bit of HTML that allows you to click on a text label instead of directly on a form control to select. It always pisses me off when designers don’t put them in since it makes forms much easier to interact with.

So, you may have tried to wrap a <label> around an image, like so:

Try clicking on the picture to select the radio box in IE or Safari: (works in Firefox, Opera, NOT in IE or Safari)

[code]

[/code]

You were probably expecting it to behave like it does when you wrap it around just text. This works as expected in Firefox and Opera (producing an effect as if you had just clicked the radio button or checkbox) but doesn’t work in IE or Safari.

The solution to make everything within your <label> activate the radio button is a simple small bit of additional javascript to add to your <label>, where radio3 is the same ID as the element you want to activate:

[code]
onclick=”document.getElementById(‘radio3’).click();”
[/code]

Now try clicking on the picture to select the radio box in IE or Safari: (works in all browsers)

[code]

[/code]

This allows you to use images in your forms to click on to select a radio button, and works in Firefox, IE, Safari, Flock, Opera.

Feedback is welcome!

5 Responses to “How to make form labels work for images in IE and Safari”

  1. Gonzo Says:

    Very usefull tip, thanks! While adapting it to my case I tried to simplify the JS code and found this to work:

    onclick=”this.firstChild.click();”
    as the input is the firsdt child node in my html code. In the above example this.lastChild.click() should do the job.

  2. Corum Says:

    A great tip for dealing with IE’s stupid implementation.

    I simplified this just at bit to:
    onlick=”document.getElementById(this.htmlFor).click();”

    Works everywhere I’ve tried it so far.

  3. colins Says:

    Thank you for your help.

  4. Alex Says:

    I found that the first solution does not work when the input type is set to “checkbox”, however the modified example from Gonzo appears to be ok.

    Thanks for the tips!

  5. David Bootle Says:

    Thanks for this great tip. However, for some reason it wouldn’t work for me… possibly to do with the strict xhtml 1.1 doctype??? I just changed .click(); to .focus(); and it worked a treat!

Leave a Reply



sell diamonds