Ok, now I came up with this JavaScript/jQuery solution. It addresses two aspects. First, to store and display the selected checkboxes when the sort order of the table is changed, the table is filtered or when you naviagte to another page and return the table again. Secondly to check and store all checkboxes on a table page when the "Select All" button on in the table head is clicked. Here I'm stuck with selecting all rows in a table, not only the ones that are displayed on one table page (with pagination on). The selected checkboxes are stored in the session storage of the browser. There is certainly room for improvement in the functions, I don't like the iteration over all rows of the table a lot, but I couldn't find a better solution yet.
Still I think it would be nice to have this kind of funtionality available in django-tables2. Maybe in some coming version?
The checkbox column is called "selvars" in my tables.py
class dataset_varsTable(tables.Table):
selvars=tables.CheckBoxColumn(accessor='pk',attrs = { "th__input": {"onclick": "toggle(this)"}}, orderable=False)
... (other table columns)
It's the integer primary key of my model
class vars(models.Model):
idvar=models.IntegerField('Var.ID', primary_key=True)
...
And the JavaScript and jQuery functions in the HTML template with the table
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var storage_name="checkedvars"; // name of session storage
// function to store/remove checked varids in session storage
function update_checkedvars(varid, check_status){
var current_checked=[];
if (sessionStorage.getItem(storage_name)){
current_checked=sessionStorage.getItem(storage_name).split(",");
}
if (isNaN(parseInt(varid))==false && check_status==true){
current_checked.push(varid);
// store checked varid in session storage without duplicates
sessionStorage.setItem(storage_name, Array.from(new Set(current_checked)));
} else if (isNaN(parseInt(varid))==false && check_status==false){
// remove unchecked varid from session storage
sessionStorage.setItem(storage_name, current_checked.filter(e => e !== varid));
}
}
// toggle button
function toggle(source) {
checkboxes = document.getElementsByName('selvars');
for(var i in checkboxes){
checkboxes[i].checked = source.checked;
update_checkedvars(checkboxes[i].value, checkboxes[i].checked);
}
}
$(document).ready( function() {
// display checkboxes according to selected varids in session storage
var current_checked=[];
if (sessionStorage.getItem(storage_name)){
current_checked=sessionStorage.getItem(storage_name).split(",");
checkboxes = document.getElementsByName('selvars');
for(var i in checkboxes){
if(current_checked.includes(checkboxes[i].value)){
checkboxes[i].checked=true;
}
}
}
// save/remove checked/unchecked varid in session storage
$(".selvars").click( function(event) {
var varid=event.target.value
var check_status=event.target.checked
update_checkedvars(varid, check_status);
});
});
</script>