Solid Performer
Solid Performer

Reputation: 21

Need to select all checkboxes and dynamically add specific event handler to each

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?

Upvotes: 2

Views: 1559

Answers (2)

Giann
Giann

Reputation: 3192

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

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

Upvotes: 0

Matt Ball
Matt Ball

Reputation: 359966

  • 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();
        });
    });
    

Upvotes: 3

Related Questions