I am writing a simple quiz application.
It was working fine until I try to edit the font for the selected radio buttonvar labelStyle = userpick.style.fontWeight;
Anyone able to spot the problem??
Also, if possibe, suggestion to improve the code?
I have made some new changes to the checkAnswer function
// define all the elements
var content = $("content");
var questionContainer = $("question");
var choicesContainer = $("choices");
var scoreContainer = $("score");
var submitBtn = $("submit");
//init variables
var currentQuestion = 0;
var score = 0;
var askingQuestion = true;
//shortcut for document.getElementById
function $(id){
return document.getElementById(id);
}
//askQuestion Function to load question into id = question
function askQuestion (){
var choices = quiz[currentQuestion].choices;
var choicesHtml = "";
//loop through chocies and create a radio button
for (var i = 0; i < choices.length; i++){
choicesHtml += "<input type = 'radio' name = 'quiz" + currentQuestion +
"' id = 'choice" + (i + 1) +
"' value ='" + choices[i] + "'>" +
"<label for ='choice" + (i + 1) + "'>" + choices[i] + "</label></br>";
}
//load the Question
questionContainer.textContent = "Q" + (currentQuestion + 1) + ". " + quiz[currentQuestion].question;
//load the choices
choicesContainer.innerHTML = choicesHtml;
//setup for the first time
if(currentQuestion === 0){
scoreContainer.textContent = "Score : 0 right answer out of " +
quiz.length + " possible.";
submitBtn.textContent = "Submit Answer";
}
}
//checkAnswer function to match user input with quiz.correctAnswer
function checkAnswer(){
//
if (askingQuestion){
submitBtn.textContent = "Next Question";
askingQuestion = false;
//determine if radio button is clicked
var userpick;
var correctIndex;
var radios = document.getElementsByName("quiz" + currentQuestion);
for (var i = 0 ; i < radios.length; i++){
if(radios[i].checked){
//if radio button is checked
userpick = radios[i].value;
}
if(radios[i].value == quiz[currentQuestion].correct){
correctIndex = i;
}
}
//if they got it right or wrong
var labelStyle = document.getElementsByTagName('label')[correctIndex].style;
labelStyle.fontWeight = "bold";
if (userpick == quiz[currentQuestion].correctAnswer) {
score++;
labelStyle.color = "green";
}else{
labelStyle.color = "red";
}
scoreContainer.textContent = "Score: "+ score + "right answers out of "+
quiz.length + " possible.";
}
function showFinalResults(){
content.innerHtml = "<h2> You've completed the quiz</h2" +
"<h2> Below are your results </h2>" +
"<h2>" + score + " out of " + quiz.length +
"questions, " + Math.round(score/quiz.length * 100) + "% </h2>";
}
}
window.addEventListener("load", askQuestion, false);
submitBtn.addEventListener("click", checkAnswer, false);
var quiz = [{"question": "Question 1: Grand Central Terminal, Park Avenue, New York is the world's",
"choices": ["A: largest railway station",
"B: highest railway station",
"C: longest railway station",
"D: None of the above"],
"correctAnswer": 0
},
{"question": "Question 2: Entomology is the science that studies",
"choices": ["A: Behavior of human beings",
"B: Insects",
"C: The origin and history of technical and scientific terms",
"D: The formation of rocks"],
"correctAnswer": 1
},
{"question": "Question 3: Friction can be reduced by changing from",
"choices": ["A: sliding to rolling",
"B: rolling to sliding",
"C: potential energy to kinetic energy",
"D: dynamic to static"],
"correctAnswer": 0
},
{"question": "Question 4: For seeing objects at the surface of water from a submarine under water, the instrument used is",
"choices": ["A: kaleidoscope",
"B: spectroscope",
"C: periscope",
"D: telescope"],
"correctAnswer": 2
},
{"question": "Question 5: Galileo was an Italian astronomer who",
"choices": ["A: developed the telescope",
"B: discovered four satellites of Jupiter",
"C: discovered that the movement of pendulum produces a regular time measurement",
"D: All of the above"],
"correctAnswer": 3
},
{"question": "Question 6: Habeas Corpus Act 1679",
"choices": ["A: states that no one was to be imprisoned without a writ or warrant stating the charge against him",
"B: provided facilities to a prisoner to obtain either speedy trial or release in bail",
"C: safeguarded the personal liberties of the people against arbitrary imprisonment by the king's orders",
"D: All of the above"],
"correctAnswer": 3
},
{"question": "Question 7: For galvanizing iron which of the following metals is used?",
"choices": ["A: Aluminium",
"B: Lead",
"C: Zinc",
"D: Copper"],
"correctAnswer": 2
}];
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head lang = "en">
<title> Quiz </title>
</head>
<body>
<div class = "page-header">
<h1>Simple Javascript Quiz</h1>
</div>
<div id = "content">
<h3 id = "question"> </h3>
<div id = "choices"> </div>
<button id = "submit">Submit</button>
<p id ="score"></p>
</div>
<script src = 'quiz2.js'></script>
</body>
</html>
userpick.style.fontWeight;
Cannot read property 'fontWeight' of undefined
That means that userpick.style is undefined.
Relevant code:
var userpick;
for (var i = 0; i < radios.length; i++)
if(radios[i].checked){
userpick = radios[i].value;
If no radio was checked, userpick.style.fontWeight would throw, but the error would be
Cannot read property 'style' of undefined
That means that there is some checked radio, so userpick is not undefined.
But userpick.style is undefined. And thats because the value of a radio is a string, and by default strings have no style property.
Probably, you want userpick to be the checked radio, not its value
var userpick;
for (var i = 0; i < radios.length && !userpick; ++i)
if(radios[i].checked)
userpick = radios[i];
However, let me introduce querySelector and the :checked pseudo-class:
var userpick = document.querySelector(".quiz" + currentQuestion + ":checked");
In this piece of your code:
var radios = document.getElementsByName("quiz" + currentQuestion);
for (var i = 0 ; i < radios.length; i++){
if(radios[i].checked){
//if radio button is checked
userpick = radios[i].value;
}
}
//if they got it right or wrong
var labelStyle = userpick.style.fontWeight;
You put the VALUE of the selected radio button in the userpick variable. The style object is only available on a DOM element. Which is not the value of said element.
If you do: userpick = radios[i]; instead, it will work.
There are a few problems.
var labelStyle = usepick.style.fontWeight;
fontWeight is a string type.
However, later, you try labelStyle.color = "green"
The color property doesn't exist in a string.
However, worse than that userpick is a string itself!
This is because userpick = radios[i].value - value is a string type.
Most Importantly - you are trying to set fontWeight or color of a radio button - there is no text node in a radio button, so it won't make any visible difference - you need to select the label associated with that button and set THAT font weight and color.
Related
Ive been developing a Simon says game recently that adds to the score if you click the correct button which there are 3,
1) green 1
2) red 2
3) trick
I've noticed that when I run the game and click the appropriate buttons only one will add to the score whilst the other two subtract from it (Regardless of what the statement says). Im unsure why this is the case and was wondering if anyone had any insights). My thought is that the if functions don't seem to correlate to the new statement that is generated.
Any suggestions are appreciated,
var answers = [
"Simon says click red !",
"Simon says click green !",
"Simon says click 1 !",
"Simon says click 2 !",
"Click green",
"Click red",
"Click 1",
"Click 2!"
];
var score = 0;
var total = document.getElementById("score");
var statement = document.getElementById("instruct");
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
function refresh(){
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
statement.innerHTML = randomStatement;
}
function pressTrick(){
if(randomStatement === "Click green" || randomStatement === "Click red" || randomStatement === "Click 1" || randomStatement === "Click2!"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}
}
function pressRed(){
if(randomStatement === "Simon says click red !" || randomStatement === "Simon says click 2 !"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}}
function pressGreen(){
if(randomStatement === "Simon says click 1 !" || randomStatement === "Simon says click green !"){
score++;
total.style.color = "green";
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
} else {
total.style.color = "red";
score--;
total.innerHTML = "Total score: " + score;
setTimeout(refresh,900);
}}
function start(){
var i = 60;
var count = setInterval(timer,1000);
refresh();
function timer() {
var display = document.getElementById("timer");
var finished = document.getElementById("heading");
if(i < 1){
clearInterval(count);
finished.innerHTML = "Game Over! Your final Score is : " + score;
display.style.color = "red";
display.style.fontWeight = "bold";
document.body.style.backgroundColor = "black";
} else if(i <= 10) {
i--;
display.style.color = " red";
display.style.fontWeight = "bold";
display.innerHTML = i + " Seconds Left";
} else {
i--;
display.style.color = "green";
display.style.fontWeight = "bold";
display.innerHTML = i + " Seconds Left";
}}}
<html>
<head>
<title> Simon Says! </title>
<link rel = "stylesheet" href = "simonsays.css"/>
</head>
<body>
</br>
<h1> Test Your Reflexes! </h1>
<div id = "heading"; class = "h2"> Click on Simon to Begin! </div>
</br>
<img src = "boy.jpg" onclick = "start()"; onclick = "timer()"; onclick = "returnStatement";/>
</br>
<div id = "instruct" class="statement"></div>
</br>
<div class = "align">
<input type = "button" class = "button2" id = "button2" value = "1" onclick = "pressGreen()"; ></input>
<input type = "button" class = "button" id = "button" value = "2" onclick = "pressRed()"; ></input>
<input type = "button" class = "button3" id = "button3 " value = "Trick" onclick = "pressTrick()";></input>
</div>
</br>
<div id = "score" class = "score"><b> Score: </b></div>
<div id = "timer" class = "timer"><b> Time left: </b></div>
<script src = "simonsays.js"></script>
</body>
</html>
Thank you!
There's just one word too much: var. In
function refresh(){
var randomStatement = answers[Math.floor(Math.random() * answers.length)];
statement.innerHTML = randomStatement;
}
the var causes a new, local variable randomStatement to be defined, and the global randomStatement remains unchanged, so all comparisons in the rest of the program use the initial rather than the refreshed value of randomStatement. Drop the var here, and it works as expected.
Is there a way to grab the values from the radio buttons? say it gets populated in the radio button and the options are Abuelos, Boogie Burger, Pad Thai, Coalition Pizza, Wild Eggs. Is there a way I can pull those values out and have it print out after hitting a submit button?
I also don't want the value to be redirected to another page. I just want it to print out below the submit button. I also don't want the user to be able to select a value after they hit the submit button
I am trying to make a voting poll where options are taken from multiple arrays and then someone can pick a value from the radio button and hit a submit button with their option printed out. That way the user can tell what they voted for.
part of the HTML code:
<form action="" id="food-form"></form>
Javascript code:
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
You can use document.querySelector('input[name=food]:checked').value to get the selected value.
var mexicanFood = ["Caliente Mexican", "Abuelos", "Luciana's"],
asianFood = ["Omoni Korean", "Super Bowl Pho", "Sichuan Chinese", "Tian Fu Asian Bistro"],
americanFood = ["Boogie Burger", "City Barbeque", "The North End BBQ", "Wolfies Grill", "Bubs", "Fire on the Monon"];
pizza = ["Coalition Pizza", "Mackenzie River Pizza, Grill & Pub", "Bazbeaux Pizza", "Mellow Mushroom"]
thaiFood = ["Pad Thai", "Jasmine Thai", "Thai Orchid"]
notCategory = ["Jamaican Reggae Grill", "Mudbugs", "Yats", "Kolache Factory", ]
breakfast = ["Wild Eggs", "Egg and I", "Another Broken Egg Cafe", "Cafe Patachou"]
function createRandomArray(arraySize) {
var allFoods = mexicanFood.concat(asianFood).concat(americanFood).concat(pizza).concat(thaiFood).concat(notCategory).concat(breakfast),
randomFoods = [];
if (arraySize <= allFoods.length) {
randomFoods = [
mexicanFood[getRandomArrayIndex(mexicanFood)],
asianFood[getRandomArrayIndex(asianFood)],
americanFood[getRandomArrayIndex(americanFood)],
pizza[getRandomArrayIndex(pizza)],
thaiFood[getRandomArrayIndex(thaiFood)],
notCategory[getRandomArrayIndex(notCategory)],
breakfast[getRandomArrayIndex(breakfast)]
]; // at least one from each
// remove the ones that were initially added from each
allFoods.splice(allFoods.indexOf(randomFoods[0]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[1]), 1);
allFoods.splice(allFoods.indexOf(randomFoods[2]), 1);
for (var i = 0; i < arraySize - 3; i++) {
var randomIndex = getRandomArrayIndex(allFoods);
randomFoods.push(allFoods[randomIndex]);
allFoods.splice(randomIndex, 1);
}
return randomFoods;
}
return allFoods; // requesting more items of food than the amount available, so just add them all
}
function getRandomArrayIndex(array) {
return Math.floor(Math.random() * array.length);
}
var randomFoods = createRandomArray(5);
for (var i = 0; i < randomFoods.length; i++) {
document.getElementById('food-form').innerHTML += '<input type="radio" name="food" value="' + randomFoods[i] + '"> ' + randomFoods[i] + '<br>';
}
function print() {
var t = document.querySelector('input[name=food]:checked');
if (t == null)
console.log('No value selected');
else
console.log(t.value);
}
<form action="" id="food-form">
</form>
<input type="submit" id="btn" value="Submit" onClick="print()">
I am making a quiz with my son to teach him HTML. But i'm having trouble with some JavaScript(no jquery or any other libraries). Everything works okay until the end. It's suppose to tell us how many are right and wrong, but instead we get undefined.
error reads:Uncaught TypeError: Cannot assign to read only property 'innerHTML' of Question 17 of 16
HTML
<body id="body">
<div id="pokeBallL"> </div>
<div id="pokeBallR"> </div>
<div id="spacer"> </div>
<h2 id="tstat"></h2>
<div id="test"> </div>
</body>
JavaScript
(function () {
"use strict";
/*global window,alert*/
var UIlogic = {
myStuff: function () {
var pos = 0, question, test, tstat, Myquestions, btnCheck, choice, choices, chA, chB, chC, chD, correct;
Myquestions = [
["What decade wear you born?","1980's","1990's","2000's","2010's","A"],
["What activity do you like more","Gaming","Camping","Travelling","Sleeping","A"],
["Pick a color","Black","Pink","Red","Blue","A"],
["Pick a number","22","42","4","7","A"],
["Choose a weapon","Battleaxe","Sword","Daggers","pen","A"],
["Pick an animal","Tiger","Monkey","Elephant","Human","A"],
["Pick a music genre","Rock","Hip-hop","Country","Folk","A"],
["How many legs do Butterflies have?","4 legs","6 legs","2 legs","3 legs","A"],
["How many stripes are on the American flag?","13","15","7","19","A"],
["Which is the nearest star?","Centauri A","Sol","Sirius","Proxima Centauri","A"],
["Longest river in the world is...?","Mississippi","Nile","Amazon","Ohio","A"],
["Pick one...","PS4","PC Master Race","XB One","Puny Apple","A"],
["Pop or Soda?","Pop","Both","Soda","Soft Drink","A"],
["What is your favorite creature","Amphibian","Mammal","Reptile","Avian","A"],
["Pick a squad position","Squad Leader","FTL","","Grenadier","A"],
["The Zombie apocalypse has begun! CHoose your path...","Get to lifeboat","Live inside mountains","Hold-up above gas station","Become Zombie","A"]
];
function _(x) {
return document.getElementById(x);
}
function renderQuestion() {
test = _("test");
tstat = _("tstat").innerHTML = "Question " +(pos + 1)+ " of " +Myquestions.length;//seems to have an issue here
if(pos >= Myquestions.length) {
test.innerHTML = "<h2>You got " +correct+ " out of " +Myquestions.length+ " questions correct!</h2>";
tstat.innerHTML = "<h2>Test completed</h2>";
pos = 0;
correct = 0;
return false;
}
question = Myquestions[pos][0];
chA = Myquestions[pos][1];
chB = Myquestions[pos][2];
chC = Myquestions[pos][3];
chD = Myquestions[pos][4];
test.innerHTML = "<h3>"+question+"</h3><hr />";
test.innerHTML += "<h4><input type='radio' name='choices' value='A'>"+chA+"</h4><br />";
test.innerHTML += "<h4><input type='radio' name='choices' value='B'>"+chB+"</h4><br />";
test.innerHTML += "<h4><input type='radio' name='choices' value='C'>"+chC+"</h4><br />";
test.innerHTML += "<h4><input type='radio' name='choices' value='D'>"+chD+"</h4><br />";
test.innerHTML += "<button id='btnCheck' class='btnClass'>Submit</button>";
btnCheck = document.getElementById("btnCheck");
btnCheck.addEventListener('click', checkAnswer, false);
}
renderQuestion();
function checkAnswer() {
choices = document.getElementsByName("choices");
for(var i = 0; i<choices.length; i++) {
if(choices[i].checked){
choice = choices[i].value;
}
}
if(choice == Myquestions[pos][5]) {//somewhere here doesn't seem right either.
correct++;
}
pos++;
renderQuestion();
}
}
};
window.onload = function () {
UIlogic.myStuff();
};
}());
separate this line
tstat = _("tstat").innerHTML = "Question " +(pos + 1)+ " of " +Myquestions.length;//seems to have an issue here
into this:
tstat = _("tstat");
tstat.innerHTML = "Question " +(pos + 1)+ " of " + (Myquestions.length + 1);
Demo
I got it... i changed
var correct;
to
var correct = 0;
turns out, the index wasn't counting because correct was reading NAN
Although, i should make a function to check the radios first before entering, a non-answer will answer correctly. This is what i made for that...
function checkAnswer() {
choices = document.getElementsByName("choices");
var found = 1;
for (var i = 0; i < choices.length; i++) {
if (choices[i].checked) {
choice = choices[i].value;
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
return false;
}
if (choice === Myquestions[pos][5]) { //somewhere here doesn't seem right either.
correct++;
}
pos++;
renderQuestion();
}
I'm working on a quiz app, but I can't seem to get the value or the index of the radio buttons on the page.
Here's my code:
HTML:
<div id="container">
<div id="quiz"></div>
<div id="choices"></div>
<input id="next" type="button" value="Next">
<input id="back" type="button" value ="Back">
<div id="results"></div>
</div>
JavaScript:
var allQuestions = [
{
question: "Who is the best in the world?",
choices: ["CM Punk", "John Cena", "Daniel Bryan", "Roman Reigns"],
correctAnswer: 0
},
{
question: "Who is the current WWE World Champion?",
choices: ["John Cena", "Brock Lesnar", "Triple H"],
correctAnswer: 1
},
{
question: "Where is Toronto located?",
choices: ["Ontario", "California", "Georgia", "Texas"],
correctAnswer: 0
},
{
question: "What is the largest California city?",
choices: ["Los Angeles", "San Fransico", "San Deigo", "Anahiem"],
correctAnswer: 0
}
];
var quiz = document.getElementById('quiz');
var choicesContainer = document.getElementById('choices');
var nextButton = document.getElementById('next');
var backButton = document.getElementById('back');
var score = 0;
var questionIndex = 0;
// A function to show the question.
function showQuiz() {
var currentQuestion = allQuestions[questionIndex].question;
quiz.textContent = currentQuestion;
choicesContainer.innerHTML = "";
var choicesNum = allQuestions[questionIndex].choices.length;
for (var i = 0; i < choicesNum; i++) {
var choice = allQuestions[questionIndex].choices[i];
choicesHTML = "<input type='radio' name='choice'>" + choice + "</br>";
choicesContainer.innerHTML += choicesHTML;
}
}
function checkScore() {
//var correctAnswers = allQuestions[questionIndex].correctAnswer;
var radios = document.querySelectorAll('[type=radio]');
var userAnswers;
for (var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
userAnswers = radios[i].value;
console.log(userAnswers);
}
}
}
showQuiz();
nextButton.addEventListener('click', function(){
questionIndex++;
showQuiz();
checkScore();
});
backButton.addEventListener('click', function(){
questionIndex--;
showQuiz();
});
First, I thought it was because I was calling the checkAnswers() function before the DOM was ready, but that doesn't seem the be the case so I'm stuck.
Any help, would be awesome and greatly appreciated. Thanks!
You have an error in your logic.
allQuestions[questionIndex] is undefined, when you click "next" after the last question. You need to check, if theres a question left.
and i think your selector for the radio buttons is wrong.
watch this:
javascript check radio buttons automatically
you need something like
radios = document.getElementsByTagName('INPUT');
for (var i = 0; i < radios.length; i++) {
if(radios[i].type == "radio"){
if(radios[i].checked) {
userAnswers = radios[i].value;
}
}
}
or you select only the checked element with
checkedbutton = document.querySelector("input[name='choice']:checked");
and further: you should add the answers as "value" of the button, like
<input type="radio" name="choice" value="Ontario">
this way you can get the value easy with
checkedbutton.value;
I'd like to change the value of a <h2> with its id within a "on" function but it doesn't change.
Here's the code:
<div id="boardGame">
</div>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html("<h2>Welcome to The Game of Monkeys</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' class='stres' value='Start' onclick='getSong()'></td></tr></tbody></table")
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
$("#boardGame").html('<table class="calculatrice" id="calc"> '+
'<tbody>' +
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#boardGame").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
$("#boardGame").append('<tr>' +
'<td class="calc_td_btn">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>')
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>
And it's the value of #valueScore that doesn't want to change. I think it it a scope problem but I can't get my way around it.
I can the value of #valueScore in the console or if I put the piece of code $("#valueScore").html(score) somewhere else in my JavaScript.
EDIT : added the whole code
The problem is that you're blowing away the DOM of all the elements at line 93-106 and you're re-creating them all. So the element that you're setting the score on is being destroyed and replaced with a completely different <h2>.
Instead of destroying everything (line 82 is where you replace the html of '#boardGame') you need to use JQuery to modify the buttons that already exist to give them the names of the song list.
As an alternative, try doing this:
Give all the multiple-choice buttons a class: '.choice_button'
Put a <div id="button_wrapper"> around all the buttons so that you have something to insert the new buttons into.
Instead of replacing the HTML for '#boardGame' simply destroy all the buttons: $('#button_wrapper .choice_button').remove()
Now you can insert the new buttons using that for loop just like you're doing on line 93
Now $('#valueScore') hasn't been blown away so the score should remain.
I've modified your code to get it to where I think it's what you're after:
<div id="boardGame">
</div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
json_dic = {"Too Much to Ask": "oHRjgi6sniY", "Sketchead": "GEfpkuCPjXs", "If You Were There, Beware": "ZVOwOzL9uDQ", "Plastic Tramp": "BiVXU2jt1Xo", "The Death Ramps": "p7cijGnXUJM", "Don't Sit Down 'Cause I've Moved Your Chair": "h1vYbHHhqYE", "R U Mine?": "VQH8ZTgna3Q", "2013": "O4vkZUC4VPA", "The Bakery": "P_D1Eqa2Lk4", "Potion Approaching": "Urw780t52zc", "Still Take You Home": "FKPKSK1nCKY", "Chun-Li's Spinning Bird Kick": "4lOdBxVS16o", "Come Together": "a-5tTz8flYI", "Snap Out of It": "PHoSRT2fNME", "Cigarette Smoker Fiona": "Wg89x455WK4", "Why'd You Only Call Me When You're High?": "6366dxFf-Os", "Brick by Brick": "qOTRx3ZqjjI", "Temptation Greets You Like Your Naughty Friend ": "VEWNOzgnmq0", "The Blond-O-Sonic Shimmer Trap": "EyBrLYN2Yok", "The Bad Thing": "3xTHjLf-ONg", "All My Own Stunts": "Er3r_J-mwII", "Love Is a Laserquest": "wxQVpRSxOZ0", "Dance Little Liar": "hf-B3Y3B0TQ", "Mardy Bum": "Lp1fQ51YZMM", "Stickin' to the Floor": "AQVMJkZGpSc", "Only Ones Who Know": "m-seRFY7-cw", "Crying Lightning": "fLsBJPlGIDU", "From the Ritz to the Rubble ": "givRh52Ic3A", "I.D.S.T.": "V6yORYEiLyU", "She's Thunderstorms": "tvHz5Rti0cU", "Catapult": "U3LsJMLWN2k", "Stop the World I Wanna Get Off with You": "3PyoxMSEHYI", "The Hellcat Spangled Shalalala": "dAlRXC19hmE", "Do I Wanna Know?": "bpOSxM0rNPM", "Knee Socks": "00bk5E7gecI", "That's Where You're Wrong": "tLOUVbemjro", "Leave Before the Lights Come On": "SEukS2YN9B8", "I Want It All": "SDTxuAEPfdY", "Secret Door": "ibyGhbvo94Q", "Suck It and See": "rjFGapDkSM0", "7": "R2t6vgC_OWw", "Brianstorm": "30w8DyEJ__0", "Baby I'm Yours": "EDLhMf6voq8", "Arabella": "Nj8r3qmOoZ8", "Old Yellow Bricks": "xLaeOrDmWQ4", "Don't Forget Whose Legs You're On": "qL0Z3Ly0CEw", "Riot Van": "j052-ROwPFM", "What If You Were Right the First Time?": "t2cFvzmqmwc", "Fire and the Thud": "VGlhSSP4nTk", "I Wanna Be Yours": "Y4NGoS330HE", "Mad Sounds": "J_-FwyoeV3E", "Fireside": "PG8yTUeptFU", "The Afternoon's Hat": "qbNKclt42Xc", "Reckless Serenade": "PY2FQ-LgmYo", "No Buses": "WK4wISbGvJw", "Electricity": "g-cukZ10j8A", "Little Illusion Machine (Wirral Riddler) ": "WlMzuzud8U4", "Piledriver Waltz": "njirT4N-JxU", "When the Sun Goes Down": "EqkBRVukQmE", "No. 1 Party Anthem": "83hFiC-siDs", "Evil Twin": "xwir-pg7WiA", "This House Is a Circus": "oDB-MGsWzQQ", "I Haven't Got My Strange": "a9yrz_psfLc", "Black Treacle": "1wznj4lD1Bs", "505": "ifZfUVp2chE", "Dangerous Animals": "qHe3E366_Po", "Perhaps Vampires Is a Bit Strong But..": "SjzOUf0AEiQ", "Fluorescent Adolescent": "ma9I9VBKPiw", "Library Pictures": "bmVerkoFPJU", "The View from the Afternoon": "PeQAZsyucbQ", "Despair in the Departure Lounge": "ZLS8ffCYN80", "I Bet You Look Good on the Dancefloor": "pK7egZaT3hs", "Bigger Boys and Stolen Sweethearts": "rLkikLrImnk", "Balaclava": "6LBCqG0YnTM", "Fake Tales of San Francisco": "ePg1tbia9Bg", "D Is for Dangerous": "zOlhvxPC3MQ", "Put Your Dukes Up John": "O8Wuv1WKldk", "My Propeller": "Z5vZovv8cPk", "Red Right Hand": "hcvGOUuDGXc", "One for the Road": "qN7gSMPQFss", "Joining the Dots": "wkvUl_l3o1c", "Red Light Indicates Doors Are Secured": "hdmR58BIHOg", "You and I ": "9zXkAaoBOLU", "Teddy Picker": "2A2XBoxtcUA", "Settle for a Draw": "IQ7NH2jcAAw", "Bad Woman ": "YnkJHU3qYIA", "Cornerstone": "LIQz6zZi7R0", "Fright Lined Dining Room": "qrqtD4TiO5c", "A Certain Romance": "WGyj5JyA5Ms", "If You Found This It's Probably Too Late": "SqKl1vcmvOU", "Who the Fuck Are Arctic Monkeys?": "oFeuKVkau6U", "Do Me a Favour": "lXJEDlLepD4", "You Probably Couldn't See for the Lights but You Were Staring Straight at Me": "j8iV3tK717s", "Dancing Shoes": "3aQELo7tXyI", "The Jeweller's Hands": "1rq0Ag15sAI", "Matador/Da Frame 2R": "DxoPxvJ0FNM", "Pretty Visitors": "4n7iaY22Do0", "You're So Dark": "6eoAwXkI3RA"}
var score = 0
var nb = 0
var iter = 0
var song
var start
var click
var listSongs = []
getHome()
$(document).on("click", '.calc_btn', function() {
iter++
$("#valueIter").html(iter+"/10")
if(iter == 10)
{
gameOver(score)
}
else
{
click = new Date()
time = (click.getTime() - start.getTime())/1000
if($(this).val() == song){
if(time <= 15)
score += parseInt((-1000/14)*time+929)
$("#valueScore").html(score)
$("#valueScore").css( "color", "green" )
}
else
{
$("#valueScore").html(score)
$("#valueScore").css( "color", "red" )
}
nb += 1
getSong()
return false;
}
})
function getHome()
{
score = 0
iter = 0
listSongs = []
$("#boardGame").html(
'<h2>Welcome to The Game of Monkeys</h2>'+
'<table class="calculatrice" id="calc">' +
'<tbody>' +
'</tbody>' +
'</table>' +
'<div id="gameButtons" style="display: none;">' +
'<h2 id="valueScore">0 points</h2>' +
'<h2 id="valueIter">0/10</h2>' +
'<input type="button" class="stres" onclick="getHome()" value="Restart">' +
'</div>' +
'<input type="button" class="stres" value="Start" onclick="getSong()">'
)
}
function getSong()
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song = keys[ keys.length * Math.random() << 0 ];
listSongs = [ song ]
url = json_dic[song]
while(listSongs.length <= 4)
{
var keys = [];
for (var prop in json_dic) {
if (json_dic.hasOwnProperty(prop)) {
keys.push(prop);
}
}
song_random = keys[ keys.length * Math.random() << 0 ];
listSongs.push(song_random)
}
// adds the music player, of course
$('#calc tbody').html (
'<tr>' +
'<td class="calc_td_btn">' +
'<div style="position:relative;width:380px;height:25px;overflow:hidden;">' +
'<div id="yt_video" style="position:absolute;top:-276px;left:-5px">' +
'</div>' +
'</div>' +
'</td>' +
'</tr>');
// adds the multiple choice buttons
for(var i = 0; i <= 4; i++)
{
var randomIndex = Math.floor(Math.random() * listSongs.length);
var randomString = listSongs[randomIndex];
$("#calc tbody").append('<tr>'+
'<td class="calc_td_btn">' +
'<input type="button" class="calc_btn" value="'+randomString+'">' +
'</td>' +
'</tr>')
var index = listSongs.indexOf(randomString);
listSongs.splice(index, 1);
}
// shows the score and the restart button
$('#gameButtons').show();
var nb = getRandomInt(0,100)
$("#yt_video").html("<iframe src='https://www.youtube.com/embed/"+url+"?autoplay=0&start="+nb+"' id='yt_video' width='380' height='300'></iframe>")
start = new Date()
}
function getRandomInt (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function gameOver(score){
$("#boardGame").html("<h2>You scored "+score+" points</h2><table class='calculatrice' id='calc'><tbody><tr><td class='calc_td_btn'><input type='button' onclick='getHome()' class='stres' value='Restart'></td></tr></tbody></table")
}
</script>
</body>
</html>
Oh I think I see the problem. You do not need to use the .html function.
Using jQuery:
$("#valueIter").val(iter+"/10");
$("#valueScore").val(score);
The html function is used to populate an element with raw html. The difference here is that jQuery provides .val() and .text() as getters and setters for any element which equate to the javascript equivelent of
element.value = score;