JavaScript : Making CheckBox Text Labels Clickable
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:
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.
- prototype Javascript Framework - full version, official site
- prototype.lite - I use this smaller lightweight version