Reputation: 73
I'm really new to JavaScript and HTML so sorry for the basic question. Basically I have this HTML file which is supposed to run my file script.js when it is loaded, my friend told me to use a $(function () { ) to contain the code so when I load the page it will run the whole script. However nothing is happening when I run the script, the create webpage is supposed to set text in the div id = question_text after an array of objects is loaded into the the array questions.
Here is the head of my HTML as you can see I have added in script.js
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/bootstrap-theme.min.css">
<link rel="stylesheet" href="../css/bootstrap.min.css">
<script src="../js/script.js"></script>
<title>Patient Questionnaire</title>
</html>
And here is my JavaScript
$(function() {
questions = [];
count = 0;
addQuestions();
createWebpage();
function Question(questionText, possibleAnswers, chosenAnswer) {
this.questionText = questionText;
this.possibleAnswers = possibleAnswers;
this.chosenAnswer = chosenAnswer;
}
function addQuestions() {
var question1 = new Question(
"Do you have or have you ever had 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 createWebpage() {
document.getElementById("question_text").innerHTML = questions[1].questionText;
console.log("questions")
}
});
I've only used JavaScript a few times before but normally I have been able to get it working by getting the elementID and setting it to what I want.
Any help would be greatly appreciated!
Upvotes: 1
Views: 63
Reputation: 8355
Put alert('Start');
in the first line of your JavaScript file to see if it gets loaded at all.
As SLaks said, for $
to work, you need jQuery. So you need to load that too.
Upvotes: 0
Reputation: 1570
You have to use the following syntax in order to get your Javascript code executed:
(function(){
...
})();
Here is a working fiddle: http://jsfiddle.net/470sk1gd/
In my opinion there's no need to use jQuery in this case.
Upvotes: 1