I'm trying to get a prototype for a system finished, however I couldn't find a way to stop my global variables initializing when I reload the script. When I'm writing my full system I will be making use of localStorage etc, but for now I'm just trying to find a quick fix to stop the variables and functions from executing every time I load the script.
$(function() {
questions = [];
count = 0;
addQuestions();
var originalHtml = document.body.innerHTML;
$(document).ready(createWebpage);
$(document).ready(createAnswerPage);
function Question(questionText, possibleAnswers, chosenAnswer) {
this.questionText = questionText;
this.possibleAnswers = possibleAnswers;
this.chosenAnswer = chosenAnswer;
}
function addQuestions() {
var question1 = new Question(
"Do you have or are you being treated for high blood pressure?",
['Yes','No'],
""
);
var question2 = new Question(
"Within the last year, have you had chest pain or pressure with activity such as walking or climbing stairs?",
['Yes','No'],
""
);
var question3 = new Question(
"Do you currently take medication to prevent or reduce agnia (chest pain from the heart)?",
['Yes','No'],
""
);
var question4 = new Question(
"Have you ever had a heart attack?",
['Yes', 'No'],
""
);
questions.push(question1);
questions.push(question2);
questions.push(question3);
questions.push(question4);
}
function submitFunction() {
if ($('input[name=answerValue]:checked', '#buttons').val() != null) {
questions[count].chosenAnswer = $('input[name=answerValue]:checked', '#buttons').val();
console.log( questions[count].chosenAnswer);
count++;
if (count < questions.length) {
document.body.innerHTML = originalHtml;
createWebpage();
} else {
location.href= '../src/answerpage.html';
}
} else {
alert("Please select an option");
}
}
function createAnswerPage() {
for (var i = 0; i < questions.length; i++) {
$('#question_section').append("<h1>" + questions[i].questionText + "</h1>");
$('#answer_section').append("<h1>" + questions[i].chosenAnswer + "</h1>");
console.log(questions[i].chosenAnswer);
}
}
function createWebpage() {
$('#question_text').append("<h1>" + questions[count].questionText + "</h1>");
console.log("questions");
for ( var index = 0; index < questions[count].possibleAnswers.length; index++) {
console.log(questions[0].possibleAnswers[index]);
$('#buttons').append("<input type='radio' name = 'answerValue' value=" + questions[count].possibleAnswers[index] + ">" + questions[count].possibleAnswers[index] + "<br>");
}
$('#answer_text').append("<br> <br> <br>");
$('#answer_text').append("<button id = 'nextPage'>Next</button>");
$('#nextPage').bind("click",submitFunction);
}
});
It is in the submit function where I load the new webpage and I am trying to use questions[i].chosenAnswer when the script reloads, but every time I run the script it is making me run the addQuestions() function which replaces all the objects in my array with the original data.