Reliable javascript checkbox events

May 18, 2011

0 minute read


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.


Share as Tweet || Share on LinkedIn
Post source code on GitHub - suggestions & PRs welcome!
Subscribe for updates on software development, contracting, side projects, blog posts and who knows what else. Read the archives for an idea of content.

Mailing list powered by the excellent buttondown.email.