Question regarding parent/child relationships with dynamically generated checkboxes using jquery
I have a form of checkboxes, that is dynamically generated based on the users content. Sections of checkboxes are broken up by categories, and each category has projects within. For database pu开发者_运维问答rposes, the category values have checkboxes, that are hidden. IF a category has sub items that have checkboxes that are checked, THEN the category checkbox is checked as well.
I have gotten this working ok using the JQuery .click(), but I can't figure out how to do it when the page loads.
Here is my code for when a checkbox is actually clicked:
$(".project").click(function() {
if($(this).is(":checked") && $(this).hasClass("project")) {
$(this).parent().parent().children(':first').attr('checked', true);
}else if(!$(this).parent().children('.project').is(":checked")){
$(this).parent().parent().children(':first').attr('checked', false);
}
});
Now when I am editing the status of these boxes (meaning after they have been saved to the db) the category boxes are not showing up as checked even though their children projects are checked. What can I do to make it so that my category box will be checked at load time if that category's child is checked?
Part of the problem I think is with the dynamically changing parent child setup, how can I find the parent box in order to have it checked? Thanks!
EDIT:
Let's say the parent elements have a unique class.
<div class="parent">
<input type="checkbox" />
<div>
<input type="checkbox" class="project" checked="checked" />
</div>
<div>
<input type="checkbox" class="project" />
</div>
</div>
You could do something like this on page load:
$('.parent:has(.project:checked)').children(':first').attr('checked','checked');
This will return .parent
elements that have at least one descendant that has class project
and is checked.
Docs for the :has selector http://api.jquery.com/has-selector/
If you want to run the click
handler when the page loads, you can trigger it manually.
$(".project").click(function() {
if($(this).is(":checked") && $(this).hasClass("project")) {
$(this).parent().parent().children(':first').attr('checked', true);
}else if(!$(this).parent().children('.project').is(":checked")){
$(this).parent().parent().children(':first').attr('checked', false);
}
});
$('.project').click(); // Triggers the click event handler
This is shorthand for:
$('.project').trigger('click'); // Accomplishes the same as above
I'd recommend using the live() method for binding your triggers, it's designed to apply binding to dynamically created elements.
精彩评论