0

I'm looking for a quick script to change a div when a checkbox is checked.

For example: Check the checkbox and "div1" appears. Uncheck the checkbox and "div2" appears.

Visual example: http://www.mmo-champion.com/ Take a look at there "Recent Forum Posts" box. I'm looking for something exactly like that.

Thanks!

Bryan
  • 1
  • 1

2 Answers2

1

Please see the code below:

$("#cbox").click(function() {
   if ( $(this).is(':checked') )
   {
     $("#div1").show();
     $("#div2").hide();
   }
   else
   {
     $("#div1").hide();
     $("#div2").show();
   }    
});
Eray Balkanli
  • 6,960
  • 9
  • 39
  • 65
Vertigo
  • 2,674
  • 1
  • 21
  • 24
  • Worked perfectly. Now is there a way to save the users option in there cookies? So that when they revisit the page the checkbox remains the same? – Bryan May 28 '11 at 10:17
  • Hmm, the code doesn't seem to work in IE. There a work around for that? – Bryan May 28 '11 at 10:24
  • Yeah, doesn't work on my IE8, odd. My CMS uses prototype so I had to change all the $'s to "jQuery" could that cause anything? Also, do you know anything about cookies? I'd like to set this up so that the div and checkbox the user leaves it at remains the same upon page reload. – Bryan May 28 '11 at 13:07
  • Fixed the IE 8 issue, just had to update jQuery. Still seeking help for the cookies though! =) – Bryan May 28 '11 at 13:26
  • Check this question: http://stackoverflow.com/questions/1458724/how-to-set-unset-cookie-with-jquery – Vertigo May 29 '11 at 09:26
1

You could try:

$('#checkboxID').click(
    function(){
        $('#div1, #div2').toggle();
    });

JS Fiddle demo

This assumes that the div1 is hidden, and div2 is shown, on page-load and the first click will check the checkbox and therefore show the divs.

References:

David says reinstate Monica
  • 230,743
  • 47
  • 350
  • 385