I currently have a list of checkboxes spread over several pages (pagination), the values of which need to be stored in local storage so that I can list them all elsewhere on another page. I am therefore attempting to store all of these values in an array, and constantly update that array by adding/removing values depending on whether or not the checkboxes have been clicked.
I am currently using the following:
var brochuresList = [];
jQuery('.brochure-select-checkbox').on('click', function () {
var brochure, brochures = [];
jQuery('.brochure-select-checkbox').each(function () {
brochure = {id: jQuery(this).attr('id'), checked: jQuery(this).prop('checked'), value: jQuery(this).val()};
brochures.push(brochure);
});
localStorage.setItem("brochures", JSON.stringify(brochures));
for (var i = 0; i < brochures.length; i++) {
if( jQuery('#' + brochures[i].id).is(':checked') && !brochuresList.includes(brochures[i].value) ){
brochuresList.push(brochures[i].value);
} else (!jQuery('#' + brochures[i].id).is(':checked')) {
var index = brochuresList.indexOf(brochures[i].value);
brochuresList.splice(index, 1);
}
}
console.log(brochuresList);
});
However I seem to be having some odd behaviour. With all checkboxes 'unchecked', the console prints an empty array, which is correct. If I then click the first checkbox in the list, the console still returns an empty array - which is wrong. If I click another checkbox, I get both checkboxes in the array which is correct. Can anyone see in the above where I'm going wrong?
changerather thanclickfor reading checkbox events.