Linda725
Linda725

Reputation: 4167

jquery function with parameters

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?

Upvotes: 1

Views: 16038

Answers (1)

Jacob Relkin
Jacob Relkin

Reputation: 163318

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

Upvotes: 11

Related Questions