开发者

Why is my array losing its contents when I refresh the page?

I have created an:

var checkboxFarm = new Array();

then I want to record a checkbox status in that array, as there are 11 checkboxes.

Button.addEventListener("click", function() {

          rp_farmAtivada(index);

        }, false);

when clicked change the variable in the array:

function rp_farmAtivada(index) {
     checkboxFarm[index] = !checkboxFarm[index];
};

but every time I refresh the page it loses all the checkboxes status and I'm aware that all that array gets the "undefined" value.

the checkboxFa开发者_运维技巧rm array is defined in the beginning of the script, so it should have a global scope.

Am I missing something?


You will need to save the status of the checkboxes to be able to refresh and keep their state, as HTTP is stateless.

You could add some AJAX on click to save the results to a database, or to a cookie.

Then on DOM ready, you could retrieve these previous results and change the checkbox values accordingly (or alternatively use a server side language to echo the default states in the markup).

Update

Your comment on LukeN's answer...

can I define the default value for all the array 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 it working online at JSbin.


That's just how it works. If you want to save state, use cookies. Or generate the values inside a server sided script and echo them to the Javascript.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜