mkaz.com home photography web dev about

JavaScript : Making CheckBox Text Labels Clickable

Author: Marcus Kazmierczak
Created On: January 29, 2002
Last Modified: May 29th, 2006

Updated Script: More generic and more simple. :)

The following script makes checkboxes in HTML forms behave like standard computer interfaces; specifically when the text label is clicked it will check the box.

Here's an example:

Select which items you want:

Item 1 - test 1
Item 2 - test 2
Item 3 - test 3
Item 4 - test 4
JavaScript Code

The previous script relied on specific names for the form and checkbox elements, the key to making this much easier was by using the prototype library to select the elements simply by using the CSS id name.

For example, the HTML:

<input id=item1 type="checkbox" ...>

That element can be selected in Javascript using the prototype lib like so:

	elem = $("item1");

So that simplifies the script to:

<script type="text/javascript" src="/js/prototype.lite.js"></script>
<script type="text/javascript">

function cbsel(item)
{
    fe = $(item);
    if (fe.checked) { fe.checked=false; }
    else { fe.checked = true; }
}

</script>

With the HTML:

<input id=item1 type="checkbox" name="cb" value="item1">
<span class=label onClick="cbsel('item1')">Item 1 - test 1</span>

I added a nice touch of changing the cursor to the standard pointer when you mouse over the links. This was done using the following bit of CSS

<style type="text/css">
    .label { cursor: pointer; }
</style>

To see it all put together: View Source of this page.

Remember you must download and include the prototype framework
Related Links
You can download the library from either spot, both will work: