I am working on a page with a list of checkbox in my contact form. What I want to do with my input values is I want to store this on a localStorage key. When I tried to do it, it worked. It was submitted to confirm page. But when I went back to my previous page, the checked input checkboxes were really checked. But when I try to uncheck the checked checkbox, the value is still saved in my localstorage but it went down to the last element of my array.
Here is my html structure:
<input
id='item3'
name='check-item'
value='Item1'
type='checkbox'
/>
<input
id='item3'
name='check-item'
value='Item2'
type='checkbox'
/>
<input
id='item3'
name='check-item'
value='Item3'
type='checkbox'
/>
here are also my javascript codes:
var boxes, arr;
// This function loads the array and then checks the uid of each checkbox
// against it.
function checkBoxes() {
var getArr = loadBoxArray();
$.each($('input[name=check-item]'), function (i, el) {
for(var ctr=0; ctr<getArr.length; ctr++){
if ($(this).val() === getArr[ctr]) {
$('input[value='+getArr[ctr]+']').prop('checked', true);
} else {
$('input[value='+getArr[i]+']').prop('checked', false);
}
}
});
}
// If the localStorage item is available, load it into an array
// otherwise set a default array and save it to localStorage
const loadBoxArray = () =>{
if (localStorage.getItem('boxes')) {
arr = JSON.parse(localStorage.getItem('boxes'));
return arr;
} else {
arr = [0, 2];
saveBoxArray(arr);
return arr;
}
}
// Save the array to localStorage
function saveBoxArray(arr) {
arr = [...new Set(arr)]
localStorage.setItem('boxes', JSON.stringify(arr));
}
// On page load check the boxes found in localStorage
checkBoxes();
// Clicking a checkbox will update the checkbox array which is then saved to localStorage
$('input[name=check-item]').click(function () {
var arr = $.map($('input[name=check-item]:checked'), function (el) {
return $(el).val();
});
saveBoxArray(arr);
});
What could be wrong in my code? I am working on this for almost 4hrs already and I haven't solved this issue.