Karz
Karz

Reputation: 557

Keep a var when updating the code

I wanna make a thing in javascript and html and I've got a problem.

I've a selection page where I can click on 8 different buttons, and I want a var to take the id of this button. This button throw me on an other page, which have to use this var.

The problem is that when the code is called once again in the second page (to return the var in my main function otherwise it's not working), this code is updated and my var is obviously reset to 0;

I want to keep the value of this var when I call it again in my other page.

Thank you !

levelSelected = 0;

// Récupère le click 
for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html';
    });
}

Upvotes: 0

Views: 47

Answers (2)

Crembo
Crembo

Reputation: 5438

One way of doing it beside localStorage or cookies is to pass it in the URL, i.e. using parameters:

levelSelected = 0;

// Récupère le click 
for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html?levelSelected=' + levelSelected;
    });
}

Have a look at How to retrieve GET parameters from javascript? to see how you can later retrieve the parameters in the next page.

Also How can I get query string values in JavaScript? as Terry suggested in the comments in your answer.

Edit:

Just in case you're not familiar with GET properties - you have have any number of them, just the first one must be preceded by a ? while all the other ones must be preceded by a &.

So:

location.href='level.html?levelSelected=' + levelSelected + '&otherParam' + paramValue;

Upvotes: 2

Peter Jewicz
Peter Jewicz

Reputation: 666

Try local storage.

for (var i = 0; i < 8; i++) {
    $('#level' + i).click(function() {
        levelSelected = this.id;
        console.log(levelSelected);
        location.href='level.html';
        localStorage.id = levelSelected;
    });
}

Then on the page you want to use it on call the var back.

localStorage.getItem('levelSelected');

Upvotes: 1

Related Questions