0
votes

I have some nice stylized "checkboxes," that are actually made up of li span and a bootstrap glyphicon. When they get "checked", they get a .active class.

When the active class is triggered, it reveals a div below the bootstrap looking checkbox and the div contains more checkboxes.

The problem is, if a user checks these, but unchecks the bootstrap checkbox, the smaller checkboxes will still be checked (but hidden). If they're still checked, my PHP backend code still picks it up as checked and puts that unwanted data in the database.

I would just do a prop("checked", "false"); on the smaller checkboxes when the bootstrap checkbox is not .active, but there comes a bigger problem with the fact that these are dynamically generated, and there could be multiple big bootstrap checkboxes that reveal a div below them with other checkboxes.

SO ENOUGH OF THE DESCRIBING, here's a jsfiddle: http://jsfiddle.net/5fw60gLv/1/

For example purposes, I just have 2 big checkboxes that contain a hidden div below them and it reveals when the big checkbox is checked.

Here is the jQuery code that I'm using to reveal the hidden divs, and hide the revealed divs (which also is supposed to uncheck the checkboxes)

$('li.level-1-checkbox').click(function () {
    if ($(this).hasClass('active')) {
        $(this).next().fadeIn(300);
    } else {
        $('.level-1-checkbox').find('div').prop('checked', false);
        $(this).next().fadeOut(300);

    }
});
1
TLDR, Gregory. Where's the question mark?Phil Tune
What about assigning them a unique class when generated? something like class="parentName-x" where x is an incremented value or something similar?Pseudonym
@philtune When the bigger checkboxes are unchecked, the checkboxes that were nested below it need to disappear AND be unchecked. But they're dynamically generated, so they all have the same class.Lee White
Why is the fact that they're dynamically generated an issue?j08691
@j08691 Lets say that I do $('.level-2-checkbox').prop('checked', 'false'); when the top checkbox is unchecked. But that would mean that if I had multiple top checkboxes, just clicking one of those will uncheck ALL of the checkboxes, which it only needs to unchecked the ones that are nested below the top checkbox (because the top checkboxes are also dynamically generated and they all have the same class)Lee White

1 Answers

0
votes

You can deselect those checkboxes from when you hide the div. So, your jQuery code for revealing and hiding div would be:

$('li.level-1-checkbox').click( function() {
    if($(this).hasClass('active')) {
        $('.level-1-checkbox').find('div').prop('checked', false);
        $(this).next().fadeOut(300);
    } else {
        $(this).next().fadeIn(300); 
        $(this).next().find('input[type=checkbox]:checked').removeAttr('checked');
    }
});

Last line will find all checked checkboxes form not-active div, and remove their checked attribute.