Reputation: 3
As you can see, I am trying to use the variable counter from a function from one file in a function of another file. I defined counter in the function without beginning it with "var" which I think should make it a global variable. However, it seems it doesn't work. SOS!
//function used in symptoms.html
function checkboxes(){
counter = parseInt(document.querySelectorAll('input[type="checkbox"]:checked').length); //counter would be a global var?
if (counter>=10){
location.href='end.html';
}else{
location.href='state.html';
}
}
//function used in another file
function statedegree(x){
var conclusion=x*counter;//uses counter var from checkboxes()
if (conclusion>=18){
location.href= 'end.html';
} else{
location.href='end1.html';
}
}
Upvotes: 0
Views: 52
Reputation: 36
I don't know the order of your file, but the another file must have to be included in the html after the first which contains the declaration of the variable. In the same way, I think that your function which declare the variable must be called before the second.
Otherwise, you can use window.counter to declare your variable as global across multiple files.
Please correct me if I'm wrong
Upvotes: 0
Reputation: 1058
Persistence across different pages can be done using the localStorage API:
function checkboxes(){
localStorage.setItem('counter', document.querySelectorAll('input[type="checkbox"]:checked').length);
if (counter>=10){
location.href='end.html';
}else{
location.href='state.html';
}
}
function statedegree(x){
var conclusion=x * parseInt(localStorage.getItem('counter') || 0);
if (conclusion>=18){
location.href= 'end.html';
} else{
location.href='end1.html';
}
}
``
Upvotes: 1