1

i have several checkboxes that when checked show a hidden div. Is there a way to write a jquery function that will show or hide based on whether the checkbox is checked the hidded div?

using just javascript

<input type="checkbox" name="box1" id="box1" onclick="function toggle('div1')">
<div id='div1'>
.....
</div>

<input type="checkbox" name="box2" id="box2" onclick="function toggle('div2')">
<div id='div2'>
.....
</div>


<script>
function toggle(id) {
if (this.checked) show(id);
else hide(id);
}

where show() and hide() are functions define to change the display attribue of the id.

Is there some way to do this in jquery where I bind the toggle to the checkbox adn have it toggle an id that is passed somehow?

1 Answer 1

10

You can try creating a small jQuery plugin:

$.fn.toggleCheckboxContainer = function(selector) {
   var toggleObject = $(selector);
   return $(this).each(function() {
      $(this).change(function() {
        $(this).is(':checked') ? toggleObject.show() : toggleObject.hide();
      });
   });
};

$(function() {
    $('#box1').toggleCheckboxContainer('#div1');
    $('#box2').toggleCheckboxContainer('#div2');
});

jsFiddle example

Sign up to request clarification or add additional context in comments.

4 Comments

+1, I like it! Much nice way that what I was going to write :)
+1. But I would not prepend '#' and instead pass in a whole selector. That would make it more flexible.
would this work when the checkbox is checked or unchecked? Like an event handler?
great! thank you! I love the jsFiddle example thats what really did it for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.