简体   繁体   中英

Jquery, dynamic checkbox selecting

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM