Why is my array losing content on page refresh?
I created:
var checkboxFarm = new Array();
then I want to record the status of a checkbox in this array as there are 11 checkboxes.
Button.addEventListener("click", function() {
rp_farmAtivada(index);
}, false);
on click change the variable in the array:
function rp_farmAtivada(index) {
checkboxFarm[index] = !checkboxFarm[index];
};
but every time I refresh the page it loses all checkboxes and I know that this whole array gets "undefined".
The checkboxFarm array is defined at the beginning of the script, so it must have a global scope.
Did I miss something?
a source to share
You will need to save the status of the checkboxes so that they can update and keep their state since HTTP has no status.
You can add AJAX on click to save results to database or cookie.
Then in DOM ready mode, you can retrieve those previous results and change the checkbox values accordingly (or alternatively use a server side language to echo the default in markup).
Update
Your comment on LukeN's answer ...
Can I define the default for all arrays as true without setting it for each one?
Yes, you can. Look at this code ...
// I'm using an empty array literal here, more succinct and widespead than the old `new Array()`
var checkboxFarm = [];
// You will need to define here how many array members you want to have the `true` value
for (var i = 0; i <= 10; i++) {
checkboxFarm[i] = true;
}
See how it works online at JSbin .
a source to share