-1

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.

CoderPi
  • 12,985
  • 4
  • 34
  • 62
Alex Latham
  • 73
  • 2
  • 10
  • You need to understand that the Javascript code is static. To save data consider saving it in the backend database. Or you can even use LocalStorage/SessionStorage/IndexDB in the browser for which you dont need to send data to the backend. – Rahul Desai Nov 29 '15 at 21:46
  • Stopped reading at *"My global variables ..."*, why not just remove the globals, problem solved ! – adeneo Nov 29 '15 at 21:47
  • Yeah I learned that frankly a bit too late, I will be saving it to a database later on but I'm just needing a quick fix at the minute – Alex Latham Nov 29 '15 at 21:47
  • Then Rahul is spot on, localStorage is probably your best bet – adeneo Nov 29 '15 at 21:50
  • JavaScript is held in memory and can't be persisted after a refresh. You have to use some sort of persistent storage, like localStorage. – Josh Beam Nov 29 '15 at 21:58

1 Answers1

2

First of all, read up: Why are global variables considered bad practice?


A quick fix in your case would be to use HTML5 localStorage.

Example:

window.localStorage.setItem('myCat', 'Tom'); // save data
window.localStorage.getItem('myCat'); // get data

Here, you are using myCat as the key/variable.

Window.localStorage - MDN docs

Community
  • 1
  • 1
Rahul Desai
  • 15,242
  • 19
  • 83
  • 138
  • I am looking for it to hold an array of chosen answers though, is this possible? – Alex Latham Nov 29 '15 at 22:02
  • 1
    @AlexLatham You can always use a Javascript object to do that. Put all your answers in the object. Before saving do `JSON.stringify()`. After fetching the saved value, do `JSON.parse()`. Google them. – Rahul Desai Nov 29 '15 at 22:04