18 May 2011

Reliable javascript checkbox events


Some sites have checkboxes which show/hide another element when you click them. This a handy feature, but not all sites take into account the fact that firefox remembers the contents of a form when you reload the page (this is a good thing).

So here's how you avoid that with jQuery:

<script type="text/javascript">
$(function() {
// initialise show/hide to match the checkbox value
$('.targetelements').toggle($('#mycheckbox').attr('checked'));
// attach click handler for show/hide to checkbox
$('#mycheckbox').click(function(){ $('.targetelements').toggle(this.checked);})
});
</script>

Simples!

You could use the same principle without jQuery if you need to. Simply read the value of the checkbox with javascript the old fashioned way before deciding whether to hide when you initialise you page.

No comments: