2

Given the following repeated markup in a page:

<div>
     <input type="checkbox" id="chk1" />
     <div id="div1" >
          //stuff to toggle
     </div>
</div>
<div>
     <input type="checkbox" id="chk2" />
     <div id="div2" >
          //stuff to toggle
     </div>
</div>

How can I get all checkboxes and then dynamically add toggle to the associated div in an event handler for each checkbox?

$(document).ready(function() {
     $('input:checkbox').each(
          function() {
               $(this).bind('click", function() {
                    //Attach toggle() to associate DIV
                    //$('#div1').toggle();
               });
          });
});

Is there a simple way to do this without resorting to either parsing or assuming an ordered list of IDs?

2 Answers 2

3
  • Use the change event, since that's really what you care about
  • Use .live() so you only bind 1 listener, rather than 1 per checkbox
  • Use DOM traversal to find the <div>

    $(function ()
    {
        $('input:checkbox').live('change', function ()
        {
            $(this).next().toggle();
        });
    });
    
Sign up to request clarification or add additional context in comments.

Comments

0

You don't need the each() or bind():

$('input:checkbox').click(function (event) {
  //... using $(this)
});

1 Comment

You also don't need the .bind('click', ...) when .click(...) will do.

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.