Reputation: 139
I'm trying to have all checkboxes (as list items) in an unordered list be checked once their parent checkbox is checked.
I've looked at a lot of Stackoverflow pages and tried many approaches that seem like they should work, but don't. I'm trying to figure out why one approach worked but 3 or 4 others didn't.
Worked:
$("#" + e + "areas").find("input[type='checkbox']").each(function () {
this.checked = true;
});
Did not work:
$("#" + e + "areas").find("input[type='checkbox']").prop('checked', this.checked);
$("#" + e + "areas").find("input[type='checkbox']").each(function () {
$(this).prop('checked', this.checked);
});
This is the function in which it exists and currently works:
function toggleAreas(e) {
if (!$("#" + e + "areas").is(':visible')) {
$("#" + e + "areas").css({ 'display': '', 'list-style-type': 'none' });
$("#" + e + "areas").find("input[type='checkbox']").each(function () {
this.checked = true;
});
}
else {
$("#" + e + "areas").css({ 'display': 'none' });
}
}
HTML:
<ul style="list-style-type:none;">
<li style="list-style-type:none;">
<input type="checkbox" value="Central" id="5dept" name="5" onclick="toggleAreas("5")">
<label for="Central">Central</label>
<ul id="5areas" style="list-style-type: none;">
<li><input type="checkbox" value="Administration" id="41area" name="Administration">
<label for="Administration">Administration</label>
</li>
<li><input type="checkbox" value="Contact Center" id="39area" name="Contact Center">
<label for="Contact Center">Contact Center</label>
</li>
<li><input type="checkbox" value="Intake" id="38area" name="Intake">
<label for="Intake">Intake</label>
</li>
</ul
</li>
</ul>
Upvotes: 0
Views: 959
Reputation: 3795
Actually when you typing $("#" + e + "areas").find("input[type='checkbox']")
this selector returning the collection of DOM elements so there should not this
applicable. So apply this way you should $("#" + e + "areas").find("input[type='checkbox']").prop('checked', true/false);
.
But when you typing:
$("#" + e + "areas").find("input[type='checkbox']").each(function () {
this.checked = true;
});
That means each
function iterating on each item of DOM element so why we getting this
here.
Upvotes: 1
Reputation: 316
The code below didn't work because this.checked
outside the loop is undefined.
$("#" + e + "areas").find("input[type='checkbox']").prop('checked', this.checked);
This works:
$("#" + e + "areas").find("input[type='checkbox']").each(function () {
$(this).prop('checked', this.checked);
});
The this
variable is existing in the loop because each()
set every loop this
to an element from the array that you got when doing $("#" + e + "areas").find("input[type='checkbox']")
Upvotes: 0