jQuery - Check checkbox

http://www.romeotovaradero.com/branches/sites/dev/form.html

Hi SitePoint community,

Here’s what I am trying to achieve with this page*. Everytime I check a “Sub-cat”, I need "Category #1 " to be checked automatically as well as the checkbox next to the product image (shoes).

There will be multiple categories but only one product image per page. What is the easiest way to achieve this? I tried some things, but it didn’t work.

Thanks for your time,
Alex

The first thing to do is to attach an onclick event to the checkboxes


$(function () {
    $('div.checkbox-list input:checkbox').click(function () {
        ...
    });
});

When someone clicks a checkbox, you need to get the parent for the category that the checkbox belongs to. This lets you restrict things to the checkboxes within only that chosen category.


var parent = $(this).parents('div.checkbox-list');

Then you work out if the category heading should be active, then set its checked attribute accordingly.


var active = $('div input:checked', parent).length > 0;
$('h4 input:checkbox', parent).attr('checked', active);

Before that though, you could also watch for when the heading checkbox is clicked, so that you can check or uncheck all of the subcategory checkboxes.


if ($(this).parents('h4').length > 0) {
    $('div input:checkbox', parent).attr('checked', $(this).attr('checked'));
}

Here’s the script in full:



$(function () {
    $('div.checkbox-list input:checkbox').click(function () {
        var parent = $(this).parents('div.checkbox-list');
        if ($(this).parents('h4').length > 0) {
            $('div input:checkbox', parent).attr('checked', $(this).attr('checked'));
        }
        var active = $('div input:checked', parent).length > 0;
        $('h4 input:checkbox', parent).attr('checked', active);
    });
});

Awesome! Much much appreciated! I will definitely try this tomorrow morning! I wish I could understand more clearly all that javascript!

Thank you again! :slight_smile:

Works very well. The only thing I can’t figure out how to do (see my page) is when a checkbox in the “checkbox-list” is checked then check the checkbox for #product …ummm?

Since there’s only one product per page I guess I can only check that box by default using this?

$(‘#product input:checkbox’).attr(‘checked’, true);