Author: Gustav Aagesen
Go back to the tutorial page.
<ul> <li><input type="checkbox" /> Element 1 </li> <li><input type="checkbox" /> Element 2 </li> <li><input type="checkbox" /> Element 3 </li> </ul>
What we have done here is removing the precending list-button to each list element. In addition we have added a very important css-property: We have added the cursor: pointer style to indicate to the user that the label is in fact clickable.
<style type="text/css"> ul.input li{ list-style:none; margin-left:0px; cursor:pointer; } </style> <ul class="input"> <li><input type="checkbox" /> Element 1 </li> <li><input type="checkbox" /> Element 2 </li> <li><input type="checkbox" /> Element 3 </li> </ul>
What we end up with here is a list element containing the input. We want to add an event to the list element in which we locate and change the status of the checkbox.
One problem will occur when the user clicks the input itself and not the text. First the input value will change and then the list event will be triggered.
In order to handle this we will need to add an event to the input element aswell.
We want to keep the code as generic as possible. And with this accessing the input through the DOM directly.
We will need two JavaScript functions. One to toggle the value of the element and one to locate the element. I have called these toggle and toggle_child
<ul class="input"> <li onclick="toggle_child(this);"><input onclick="toggle(this);" type="checkbox" /> Element 1 </li> <li onclick="toggle_child(this);"><input onclick="toggle(this);" type="checkbox" /> Element 2 </li> <li onclick="toggle_child(this);"><input onclick="toggle(this);" type="checkbox" /> Element 3 </li> </ul>
All the JavaScript functions is to set the checked value of the element to the opposite of the current.
<script type="text/javascript"> function toggle(e){e.checked = !(e.checked);} function toggle_child(e){toggle(e.firstChild);} </script>
I have added all the code needed to a separate file for download.
You can also test the functionality below:
In this example I have showed how a little code and events can add extended usability to your web forms.
The same method can be applied on radio buttons.
Questions or feedback can be set to tormel@gmail.com
Go back to the tutorial page.