I have a list of checkboxes which generate tables when checked. Each table has an All checkbox which when clicked selects all the options of the table. The all checkboxes are all referred to by the same class but have different IDs depending on the table. I am trying to write a code to get the ID of the generated table and use this ID in my select_all function which would allow the ALL checkbox to only affect its respective table's options.
What I currently have
ALL Checkbox
<div class="Row">
<div id="topRow">
<input type="checkbox" name="tbl" class="tblall" id="all<?php echo $tables_index;?>" value="" />
<p >ALL</p>
</div>
ALL Function
$(function () {
$(document).on("click", (".tblall"), function () {
var className = $("input:checkbox[name='tbl2']").attr('class');
if (this.checked) {
// Iterate each checkbox
$('.' + className).each(function () {
this.checked = true;
});
} else {
$('.' + className).each(function () {
this.checked = false;
});
}
});
});
What I have tried
I tried to store the ALL checkbox ID in a variable and the use this variable to refer to the checkbox in my function like below:
some function (){
var allID = $(".tball").attr('id');
store allID;
}
$(function () {
var allID = window.sessionStorage.getItem("allID");
$(document).on("click", ("#"+ allID), function () {
This was not successful as it didn't even select all options of any table.
I also thought if writing a function that fetches the ID and calling the function when the DOM is loaded :
function all_Id() {
var allID;
if ($("input:checkbox[name='tbl[]']:checked")) {
allID = $("input:checkbox[name='tbl']").attr('id');
}
return allID;
}
$(document).ready(function () {
all_Id();
});
$(document).ajaxComplete(function () {
all_Id();
});
What's the best way to achieve what I want?