Skip to main content
Code Review

Return to Revisions

2 of 2
deleted 175 characters in body; edited title
Jamal
  • 35.2k
  • 13
  • 134
  • 238

Show/hide checkbox div on change and load

I'm working on a show/hide div with checkbox on change and on load. I've come up with this so far:

jsFiddle

$(document).ready(function() {
var $cbtextbook = $('#in-product_category-14'),
 $cbimod = $('#in-product_category-15'),
 $mb1 = $('#mbtextbook'),
 $mb2 = $('#mbimod');
function tbmb() {
 if ($cbtextbook.is(":checked")) $mb1.show();
 else $mb1.hide();
}
function immb() {
 if ($cbimod.is(":checked")) $mb2.show();
 else $mb2.hide();
}
tbmb();
immb();
$cbtextbook.change(tbmb);
$cbimod.change(immb);
})​

At the moment, I'm not worrying about dynamically changing elements (although I might in the future as I learn more).

Is there a much cleaner way to do this? I did get pretty simple toggle to work, but that didn't take into account if the box was already checked on page load, and the div I wanted to show/hide could get off cycle (i.e. show when unclicked, hide when clicked) if it was already checked, so I came up with this overly verbose solution. How can I pare this down?

default

AltStyle によって変換されたページ (->オリジナル) /