Styled checkboxes and radiobuttons

With the use of CSS and unobtrusive javascript we can do exactly what we want with checkboxes and radiobuttons.

This work was inspired by Philip Howard Styled Form Controls.

Examples

With something as simple like:

<input class="heart" type="checkbox" name="input-name" />

We can provide something as cool as.

Below are some examples with checkboxes and radiobuttons, try to hit the button below to see that the form is really posted.

Checkboxes

The first example here has the attribute checked="checked" to it as well, to show that this is working too.

Radiobuttons

Can I change or add images?

Ofcource, its realy simple. You just have to do a small change in the javascript and add some CSS.

In the javascript look around line #20 for this

switch (elements[i].className) {
    // Add other cases here for other symbols you want. Just remember 
    // to change in your css too.
    case 'heart':
        createAlternateCheckboxOrRadiobutton(elements[i], i);
    break;

You can add as many cases you like here, the name of the case is the same as the class you use when you are calling on the checkbox or radiobutton.

A example case could look like this.

case 'star':
    createAlternateCheckboxOrRadiobutton(elements[i], i);
break;

With the example above with the star case, you have to add the classes star and star-default to your CSS. The star-default class is the class that is used when the checkbox or radiobutton isn't checked.

.star { background: url(star.png) no-repeat; }
.star-default { background: url(star-default.png) no-repeat; }

When you are done with that you could just call your input with this.

<input class="star" type="checkbox" name="input-name" />

Do labels work?

Naa, not exacly, but I do hope that someone out there could solve this, so I just commented out the lines that I was experimented with. I also wanted to release what I had before my vacation and trip to Berlin.

Which browsers does it work on?

I have just tested it with:

I have a bug to report or a patch, do you want it?

Yes please! Contact me throw johan at this domain. I also want to hear which browsers this work on.

Download

You can download this zip file that contains the example above and all the images, the CSS and the javascript that the example depends on.

You also might want to read the Original post on my blog.

Changelog

2006-04-18
Todd Tyree fixed bugs with multiple radiobutton groups.
2005-07-24
First release.

Created, 24 July 2005
Updated, 18 April 2006