Reputation: 21
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
Reputation: 3192
You don't need the each()
or bind()
:
$('input:checkbox').click(function (event) {
//... using $(this)
});
Upvotes: 0
Reputation: 359966
change
event, since that's really what you care about.live()
so you only bind 1 listener, rather than 1 per checkboxUse DOM traversal to find the <div>
$(function ()
{
$('input:checkbox').live('change', function ()
{
$(this).next().toggle();
});
});
Upvotes: 3