Monday, August 29, 2011

HTML Basics: Labels and inputs

I stumbled across some code the other day that made me smile. Here is essentially what was going on:

<input id="checkbox" type="checkbox" />
<label id="label" for="checkbox">My Label</label>

<script type="text/javascript">
$('#label').click(function() {
   var checkbox = $('#checkbox');
   checkbox.attr('checked', !checkbox.is(':checked'));
});
</script>

Naturally, this bit of javascript will toggle the checkbox's checked state whenever the label is clicked. There is nothing functionally wrong with this approach, except that it is wasted effort. Every browser I have ever worked with will do this automatically without any javascript. Simply associate a label with a checkbox (or radio button) and clicking the label will toggle the checkbox's checked state:


<input id="checkbox" type="checkbox" />
<label id="label" for="checkbox">My Label</label>