JS checkbox.checked vs manually checking
I have a page which is paginated to 100 results per page by php with
checkboxes beside each. I have three functions: one to select all, one to
save what was checked, and one to restore what was checked.
I don't understand why my toggle function does not work with the other
two. If I click select all (which performs a toggle()) the checked values
are not saved; however, if I click them by hand they do get saved across
pagination. I am assuming that I have to do something along the lines of
persistCheckBox(checkboxes[i].checked) to the last line of my toggle
function --which I tried and it did not work; can someone explain why?
Thanks in advance!
function toggle(source) {
checkboxes = document.getElementsByName('multi_mag[]');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function restorePersistedCheckBoxes() {
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
var el = document.getElementById(aPair[0]);
if(el) {
el.checked = aPair[1] == '1';
}
}
}
function persistCheckBox(el) {
var found = false;
var currentStateFragment = el.id + ':' + (el.checked ? '1'
: '0');
var aStatus = getPersistedCheckStatus();
for(var i = 0; i < aStatus.length; i++) {
var aPair = aStatus[i].split(':');
if(aPair[0] == el.id) {
// State for this checkbox was already present;
replace it
aStatus[i] = currentStateFragment;
found = true;
break;
}
}
if(!found) {
// State for this checkbox wasn't present; add it
aStatus.push(currentStateFragment);
}
// Now that the array has our info stored, persist it
setPersistedCheckStatus(aStatus);
}
No comments:
Post a Comment