Reputation: 120
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?
Upvotes: 1
Views: 57
Reputation: 506
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'));
});
});
Upvotes: 1
Reputation: 2871
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);
}
});
});
Upvotes: 0
Reputation: 494
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.
Upvotes: 0