1

I have a dropdown list with different categories which i've setup like this:

Main1
sub1
sub1
sub1

Main2
sub2
sub2
sub2

etc.

When I press on "Main1" all "Sub1"s will be checked, and so on. I have made a function that works.

$('.main_check_1').change(function() {

        var checkboxes = $(".check_1");

        if($(this).is(':checked')) {

            checkboxes.prop('checked', true);

        } else {

            checkboxes.prop('checked', false);

        }
    });

but only if I hard code it, it doesn't work dynamically.

(On my admin page i'll be capable of adding more and give them an id, Main"1", Sub"1" etc).

Any idea how I could do this?

2
  • 4
    Can you show the HTML? Commented Aug 9, 2015 at 9:18
  • 1
    Can you fiddle this... Commented Aug 9, 2015 at 9:21

3 Answers 3

1

Instead of giving the mains a unique classname, you could give them a unique id-name instead and a non-unique classname, for instance 'checklist'. Make sure the classnames of the subs are the same as their parent-main-id. Now you can make something like:

$('.checklist').change(function () {
    var mainCheck = this;
    $("." + mainCheck.id).each(function () {
        $(this).prop('checked', $(mainCheck).prop('checked'));
    });
});

JSFiddle

Sign up to request clarification or add additional context in comments.

Comments

0

changing your code into following might help

$(document).on('change', '.main_check', function() {
    var mainCheck = $(this),
        subChecks = mainCheck.children('.sub-check');

    if(mainCheck.is(':checked')) {

        checkboxes.prop('checked', true);

    } else {

        checkboxes.prop('checked', false);

    }
});

Just make use of "on" method.

Comments

0

This may be useful - notice how I Managed the HTML:

$('#main_check_1').click(function() {
this_box = $(this);
        var checkboxes = $('.check1');

    checkboxes.each(function(){
        checkboxes.prop('checked', true);
        if(this_box.is(':checked')) {

            checkboxes.prop('checked', true);

        } else {

            checkboxes.prop('checked', false);

        }
    });

    });

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.