jQuery closest function
Alright I know that the .closest() have been discussed before, but I have been searching, and I still can't get it working.
The situation is this. I have a table with some checkboxes and labels. Now when a checkbox is checked I want a div to appear, and disappear when unchecked. Keep in mind that this is dynamic PHP code.
I have got it working this far, but the current issue is that all the message divs appear instead of just the appropriate one.
$('[na开发者_JAVA技巧me^="check"]').click(function() {
$(".message").toggle(this.checked);
});
Now the checkboxes have names such as check1, check2 and check3. A matter of how many that is generated.
I have tried to play around with different this(), parent() and closest() functions in my attempt to select just one of the divs, but I can't get it working.
Thank you for your attention.
Edit:
The HTML that is rendered look somewhat like this (simplified)
<div style="float: left;">
<input type="checkbox" id="check1" name="check1" value="1"><label for="check1">Label for check1</label></div>
<div class="message" style="display: none; ">FOO</div>
<div style="float: left;">
<input type="checkbox" id="check2" name="check2" value="2"><label for="check2">Label for check2</label></div>
<div class="message" style="display: none; ">FOO</div>
This should work for you, with your provided markup.
$('[name^="check"]').click(function() {
$(this).parent().next(".message").toggle(this.checked);
});
Side node: you could improve your selector performance by using input[name^="check"]
so jQuery does not need to iterate through all elements.
Code example on jsfiddle.
closest()
, parent()
and all variations will only work it the check box is inside the div.
$('[name^="check"]').click(function() {
$(this).parent().next(".message").toggle(this.checked);
});
With that said, you should avoid mass adding of event handlers. Better to use delegate
$('#table_id').delegate('[name^="check"]', function() { ... });
This approach only adds one event listener, rather than on for each checkbox.
$('[name^="check"]').click(function() {
$(this).parent().children("div.message").toggle(this.checked);
});
Assuming your div and your checkbox have the same parent.
精彩评论