NOTICE
I already asked this question on my alt account David Vex; but that account is glitched out and I can't sign into it, with a StackOverflow server error with gibberish talking about ERROR:0x12084123 followed by server gibberish; so the only way to follow up with it is reasking it. Please Excuse any inconvienence.
Quote from Question (Alt Account)
WORKABLE CODE
Better than JSFiddle!
I'm trying to make a table with a tabindex for each element which onClick, it will activate the imageSelector function (unnamed). I got the code from my last question, which was given with no named function. It worked with the 'alert' variant, but I fit it for the function that I need to check the answer which, if the if(answer1.innerHTML == "Correct Answer"){document.getElementById("correctAnswer").addAttribute("display", "inline")} is active, it will know that the answer is the set correct one, and will set the image with the id="correctAnswer" to display, but then after 3 seconds it should go back to display="hidden" and re-activate the whole randomize sequence, if the button isn't already selected, which doesn't seem to work. I tried using a setTimeout() function to make it when the answer is correct/incorrect, it will set a delay to call the function that would make the image invisible and re-randomize the answers. I'll show the code, and re-explain each part after the code.
HTML
<div id="randomizer">
<div id="wordOutput">
<div id="button">
<!-- This is the button that calls the getRandom() function to create the word. --><button id="myBtn">Randomize!</button><br>
<caption>Click this button to generate a random word!
</caption>
<!-- This is apart of the Randomizer tool, which can be changed to fit the words. It will output the answers based on -->
</button>
</div>
</div>
<div id="answers" class="answers">
<table>
<p id="outputNumber" class="outputNumber">Your word will go here; Click the Randomize Button!</p>
<tr>
<td class="output" id="output1" tabindex="1"></td>
<td class="output" id="output2" tabindex="1"></td>
<td class="output" id="output3" tabindex="1"></td>
</tr>
<tr>
<td class="output" id="output4" tabindex="1"></td>
<td class="output" id="output5" tabindex="1"></td>
<td class="output" id="output6" tabindex="1"></td>
</tr>
<tr>
<td class="output" id="output7" tabindex="1"></td>
<td class="output" id="output8" tabindex="1"></td>
<td class="output" id="output9" tabindex="1"></td>
</tr>
</table>
</div>
<div id="checkAnswer">
<img id="correctAnswer" src="http://png-1.findicons.com/files/icons/1965/colorcons_smoke/128/checkmark.png" alt="correct" style="position: absolute; left: 100px; display: none;">
<img id="incorrectAnswer" src="http://png-4.findicons.com/files/icons/1008/quiet/128/no.png" alt="incorrect" style="position: absolute; right: 100px; display: none;">
</div>
</div>
This lays out the whole sequence. outputNumber is where the number will be generated then converted to a word. The button div is simple; it's where the button is. The answers div holds the table, and each element is fitted with the id for the targetting, with the tabindex for making it clickable. The checkAnswer div holds the two hidden images.
CSS
Not really important; all it contains is Daneden's animate.css (3150 lines) of code plus 10 more lines for the coloring of the page...
JavaScript
/* Has the words and their respectful answers. */
var words = [
{ word: "Fruits A-B", array: ["Apple", "Apricot", "Avacado", "Banana", "Breadfruit", "Bilberry", "Blackberry", "Blackcurrant", "Blueberry"] },
{ word: "Fruits B-C", array: ["Boysenberry", "Cantaloupe", "Currant", "Cherry", "Cherimoya", "Cloudberry", "Coconut", "Cranberry", "Cucumber"] },
{ word: "Fruits D-G", array: ["Damson", "Date", "Dragonfruit", "Durian", "Eggplant", "Elderberry", "Feijoa", "Fig", "Goji berry"] },
{ word: "Fruits G-K", array: ["Gooseberry", "Grape", "Grapefruit", "Guava", "Huckleberry", "Honeydew", "Jackfruit", "Jambul", "Kiwi fruit"] },
{ word: "Fruits K-M", array: ["Kumquat", "Lemon", "Lime", "Loquat", "Lychee", "Mango", "Marion berry", "Melon", "Miracle fruit"] },
{ word: "Fruits M-P", array: ["Mulberry", "Nectarine", "Nut", "Olive", "Orange", "Papaya", "Passionfruit", "Peach", "Pepper"] },
{ word: "Fruits P-Q", array: ["Pear", "Persimmon", "Physalis", "Plum", "Pineapple", "Pomegranate", "Pomelo", "Purple Mangosteen", "Quince"] },
{ word: "Fruits R-T", array: ["Raspberry", "Rambutan", "Salal berry", "Salmon berry", "Satsuma", "Star fruit", "Strawberry", "Tomarillo", "Tomato"] },
{ word: "Fruits U-Z", array: ["Ugli fruit", "Watermelon", "Bell pepper", "Chili pepper", "Clementine", "Mandarine", "Tangerine", "Blood Orange", "Rock Melon"] }
];
/* This function grabs the word that is outputted, then changes the answers based on that word. Change to your liking! */
function grabWord() {
var word = document.getElementById("outputNumber").innerHTML;
var wordIndex;
for (var i = 0; i < words.length; i++) {
if (words[i].word === word) {
wordIndex = i;
break;
}
}
for (var i = 1; i <= 9; i++) {
document.getElementById("output" + i).innerHTML = words[wordIndex].array[i-1];
}
}
/* This function SHOULD be working, which it does if the function is something like alert(message) but with the function I need for the image visibility and such, it doesn't work; it doesn't even give me an answer. */
var cells = document.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function () {
var word = document.getElementById("outputNumber").innerHTML;
var answer1 = document.getElementById("output1");
var answer2 = document.getElementById("output2");
var answer3 = document.getElementById("output3");
var answer4 = document.getElementById("output4");
var answer5 = document.getElementById("output5");
var answer6 = document.getElementById("output6");
var answer7 = document.getElementById("output7");
var answer8 = document.getElementById("output8");
var answer9 = document.getElementById("output9");
if(word == "Fruits U-Z") {
if(answer1.innerHTML == "Ugli Fruit") {
document.getElementById("correctAnswer").setAttribute("display", "inline")
}
else {
document.getElementById("incorrectAnswer").setAttribute("display", "inline")
}
}
})
}
I have it condensed as MUCH as possible, but for the grabWord() function, I have to keep it that long, so that each word can have answers changed manually. It's set to what it is now for example purposes.
ERROR/PROBLEM
When I click on the answer that would match the last part that would check if its right or not, it does nothing. So I check the dev console (F12 in-browser) and see no error.
Any ideas?
KEEP IN MIND
I AM USUALLY BAD AT INCLUDING DETAILS/INFORMATION. IF YOU NEED MORE DETAILS, PLEASE COMMENT POLITELY, I WILL ADD AS MUCH INFO NEEDED POSSIBLE.
Took a look at your code ... it is working. However, you are setting the attribute "display" to "inline"; if you inspect the element for correct or incorrect answer this is NOT in the style ... adjustment below.
Also, you are only given a correct or incorrect when on Fruits U-Z and there is NO correct answer ... you, in this case, are comparing "Ugli fruit" in the array with "Ugli Fruit" as a string.
var cells = document.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function () {
var word = document.getElementById("outputNumber").innerHTML;
var answer1 = document.getElementById("output1");
var answer2 = document.getElementById("output2");
var answer3 = document.getElementById("output3");
var answer4 = document.getElementById("output4");
var answer5 = document.getElementById("output5");
var answer6 = document.getElementById("output6");
var answer7 = document.getElementById("output7");
var answer8 = document.getElementById("output8");
var answer9 = document.getElementById("output9");
console.log(word, answer1.innerHTML);
if(word == "Fruits U-Z") {
if(answer1.innerHTML == "Ugli Fruit") {
document.getElementById("correctAnswer").setAttribute("style", "display:inline; position:absolute; left:100px;");
document.getElementById("incorrectAnswer").setAttribute("style", "display:none; position:absolute; right:100px;");
}
else {
document.getElementById("correctAnswer").setAttribute("style", "display:none; position:absolute; left:100px;");
document.getElementById("incorrectAnswer").setAttribute("style", "display:inline; position:absolute; right:100px;");
}
}
});
}
Related
I want to change the font color of a value in an object using JavaScript. For example, I want to change the color of "Ciao":
const Quotes = [{Text: "Hello", Author: "Him"},
{Text: "Goodbye", Author: "Her"},
{Text: "Ciao", Author: "Me"}]
I have tried doing what my other classmates have done which is to add the color key in the object:
const Quotes = [{Text: "Hello", Author: "Him"},
{Text: "Goodbye", Author: "Her"},
{Text: "Ciao", Author: "Me", "color":"red"}]
Here is my code:
<body onload="RenderQuote(0)">
<section class="full-page x-center-y-center-column">
<div id="quote-block" class="quote"></div>
<div id="author-block" class="author"></div>
<div class="navigation-buttons">
<button onclick="RandomQuote()">Random</button>
</div>
</section>
<script>
let CurrentQuoteIndex = 0;
const Quotes = [
{ Text:"Apparently there is nothing that cannot happen today.", Author:"Mark Twain" },
{ Text:"The world's most famous and popular language is music.", Author:"Henri de Toulouse-Lautrec" },
{ Text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", Author:"Albert Einstein" },
{ Text:"Life is a marathon, know when to take a break.", Author:"My Name" },
{ Text:"Take care of yourself as if you're taking care of someone else.", Author:"My Name" },
{ Text:"Remember to take your pills.", Author:"My Name" }
]
RandomQuote = () => {
CurrentQuoteIndex = Math.floor(Math.random() * (Quotes.length));
RenderQuote(CurrentQuoteIndex);
}
RenderQuote = (QuoteIndex) => {
let Quote = document.getElementById("quote-block");
let Author = document.getElementById("author-block");
Quote.innerHTML = Quotes[QuoteIndex].Text;
Author.innerHTML = Quotes[QuoteIndex].Author;
}
</script>
You need to set the style property when rendering the quote. example:
RenderQuote = (QuoteIndex) => {
let Quote = document.getElementById("quote-block");
let Author = document.getElementById("author-block");
let authorName = Quotes[QuoteIndex].Author;
Quote.innerHTML = Quotes[QuoteIndex].Text;
// set quote texts color
Quote.style.color = Quotes[QuoteIndex].color || 'black';
Author.innerHTML = authorName;
}
This will set the color if Quotes[QuoteIndex] has property color. Otherwise it will set text color to black.
Now last quote from this object:
const Quotes = [{Text: "Hello", Author: "Him"},
{Text: "Goodbye", Author: "Her"},
{Text: "Ciao", Author: "Me", color:"red"}]
will have color red
You can set color like this e.g. Quote.style.color = 'rgb(244,123,234)'
<body onload="RenderQuote(0)">
<section class="full-page x-center-y-center-column">
<div id="quote-block" class="quote"></div>
<div id="author-block" class="author"></div>
<div class="navigation-buttons">
<button onclick="RandomQuote()">Random</button>
</div>
</section>
<script>
let CurrentQuoteIndex = 0;
const Quotes = [
{ Text:"Apparently there is nothing that cannot happen today.", Author:"Mark Twain" },
{ Text:"The world's most famous and popular language is music.", Author:"Henri de Toulouse-Lautrec" },
{ Text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", Author:"Albert Einstein" },
{ Text:"Life is a marathon, know when to take a break.", Author:"My Name" },
{ Text:"Take care of yourself as if you're taking care of someone else.", Author:"My Name" },
{ Text:"Remember to take your pills.", Author:"My Name" }
]
RandomQuote = () => {
CurrentQuoteIndex = Math.floor(Math.random() * (Quotes.length));
RenderQuote(CurrentQuoteIndex);
}
RenderQuote = (QuoteIndex) => {
let Quote = document.getElementById("quote-block");
let Author = document.getElementById("author-block");
let authorName = Quotes[QuoteIndex].Author;
Quote.innerHTML = Quotes[QuoteIndex].Text;
if(authorName=='My Name') {
Quote.style.color = `red`;
} else {
Quote.style.color = `black`;
}
Author.innerHTML = authorName;
}
</script>
One approach would be to set up CSS classes for each author and then just apply the class that matches the author's name (minus the spaces because class names can't contain spaces).
Also, you are using Pascal Case (i.e. PascalCase) for your variable names which goes against convention in JavaScript. The only time Pascal Case should be used is with the names of constructor functions as a way to let others know that those functions should be invoked with the new keyword. All caps are used often (but not required) with constant names, but other than that, camel case (camelCase) should be used for identifiers.
Also, don't using inline HTML event attributes. There are a bunch of reasons not to use this 20+ year old technique that just won't die. Instead, do all your JavaScript work separate from the HTML.
document.querySelector("button").addEventListener("click", randomQuote);
let currentQuoteIndex = 0;
const quotes = [
{ text:"Apparently there is nothing that cannot happen today.", author:"Mark Twain" },
{ text:"The world's most famous and popular language is music.", author:"Henri de Toulouse-Lautrec" },
{ text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", author:"Albert Einstein" },
{ text:"Life is a marathon, know when to take a break.", author:"My Name" },
{ text:"Take care of yourself as if you're taking care of someone else.", author:"My Name" },
{ text:"Remember to take your pills.", author:"My Name" }
];
function randomQuote(){
currentQuoteIndex = Math.floor(Math.random() * (quotes.length));
renderQuote(currentQuoteIndex);
}
function renderQuote(quoteIndex){
let quote = document.getElementById("quote-block");
let author = document.getElementById("author-block");
quote.classList = "quote"; // Reset the class list
// Replace spaces in the author name with nothing and use that resulting
// string as the class name to apply to the <div> that is the quote
quote.classList.add(quotes[quoteIndex].author.replace(/\s+/g, ""));
quote.innerHTML = quotes[quoteIndex].text;
author.innerHTML = quotes[quoteIndex].author;
}
button { margin:10px 0; }
.quote { font-size:1.5em; font-weight:bold; }
.author { font-style:italic; margin-left:15px; }
/* Each author's name becomes a CSS class and each gets a color. */
.AlbertEinstein { color: green; }
.HenrideToulouse-Lautrec { color: blue; }
.MarkTwain { color: orange; }
.MyName { color: purple; }
<section class="full-page x-center-y-center-column">
<div class="navigation-buttons">
<button>Random</button>
</div>
<div id="quote-block" class="quote"></div>
<div id="author-block" class="author"></div>
</section>
I am working on my second ever Javascript project. As you can imagine, since I am still finding my feet with building projects, there are quite a few errors which I am running into (and learning from).
Let me just quickly explain what stage I am at in building the family quiz and what the problem is. I have created an array of objects which stores questions, choices and answers within each index of the array.
When the quiz starts up, there is an intro screen displaying the rules etc. The user then clicks on a "start quiz" button which transitions the screen to the first question.
The user then selects the correct answer and clicks next question. This is the stage I am at currently.
What I am trying to simply do is append the next 'choices' into the label elements. But when I click it nothing happens. Obviously I am doing something wrong.
Please can someone assist?
Many thanks!
EDIT I have been informed by a response that there was a syntax error in my forEach loop which appends the next 'choices' to the label elements. I have corrected that. However, what I am finding now is that it is only appending the first index value of every 'choices' array to every label button.
$(document).ready(function(){
var azeem = [
{
question: "What is Azeem's favourte color?",
choices: ["blue", "yellow", "red", "green"],
answer: 0
},
{
question: "What is Azeem's favourte movie?",
choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
answer: 3
},
{
question: "What was Azeem's first ever job role?",
choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
answer: 1
},
{
question: "What is Azeem's favourite dish?",
choices: ["Pasta", "Pizza", "Chips", "Curry"],
answer: 0
},
{
question: "What subject did Azeem enjoy the most in school?",
choices: ["Drama", "Science", "P.E", "History"],
answer: 0
},
{
question: "What subject did Azeem least enjoy in school?",
choices: ["Geography", "Maths", "History", "I.T"],
answer: 1
},
{
question: "Which one of these cities has Azeem travelled to?",
choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
answer: 1
},
{
question: "Which college did Azeem study in?",
choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
answer: 3
},
{
question: "Who is Azeem's favourite sports icon?",
choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
answer: 1
},
{
question: "Who is Azeem's favourite music artist?",
choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
answer: 1
},
];
var currentQuestion = 0;
var questionNumberCounter = 1;
var questionNumber = document.getElementById("questionCount");
var choices = document.getElementById("choicesSection");
var questions = document.getElementById("ques");
questions.innerText = azeem[currentQuestion].question;
// The following event listener will transition from the instructions to the first question of the quiz
document.getElementById("startquiz").addEventListener("click",function(){
$(".quiz-intro").fadeOut(600);
$(".quiz-section").delay(600).slideDown("slow");
questionNumber.innerText = questionNumberCounter;
azeem[currentQuestion].choices.forEach(function(value){
var radio = document.createElement("input");
var label = document.createElement("label");
var div = document.createElement("div");
$(div).addClass("choice");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "answer");
radio.setAttribute("value", value);
var radioID = 'question-'+currentQuestion;
radio.setAttribute('id', radioID) ;
label.setAttribute("for", radioID);
label.innerHTML = value +"<br>";
choices.appendChild(div);
div.appendChild(radio);
div.appendChild(label);
})
})
document.getElementById("submitanswer").addEventListener("click",function(){
questionNumberCounter++;
questionNumber.innerText = questionNumberCounter;
currentQuestion++
questions.innerText = azeem[currentQuestion].question;
azeem[currentQuestion].choices.forEach(function(value){
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < 5){
labels[labelCounter].innerText = value;
labelCounter++;
}
}
})
});
HTML:
<div class="container">
<h1 class="text-center">FAMILY QUIZ</h1>
<h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>
<div class="row text-center quizSection">
<div class="col-md-4 image-section">
<img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
</div>
<div class="col-md-8 quiz-intro">
<h2>INSTRUCTIONS</h2>
<ul id="instructions">
<li>This is a multiple choice quiz</li>
<li>There is only one correct answer per question</li>
<li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>
<li>There are no hints available during the process of the quiz</li>
<li>Click the 'Start Quiz' button to begin</li>
</ul>
<button id="startquiz" class="btn-small btn-success">START QUIZ</button>
</div>
<div class="col-md-8 quiz-section">
<h5>Question <span id="questionCount">1</span> of 15</h5>
<p class="text-center" id="ques"></p>
<div id="choicesSection">
</div>
<input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">
</div>
</div>
Okay so first things first, you were missing a closing parens )
The bigger issue with your code lay within two things. First, this for loop is causing an issue where every choice you iterate over you are renaming every label that name. Why? The code below goes through each choice, sure, but it then loops over every label and redefines the label's text as that choice. Take a look:
azeem[currentQuestion].choices.forEach(function(value) {
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < 5) {
labels[labelCounter].innerText = value;
labelCounter++;
}
});
Another thing you'll notice above is that you are specifically saying 5 when really the operand should be checking for an amount that's less than labels.length (this will throw an error, so once we change it we can carry on)
azeem[currentQuestion].choices.forEach(function(value) {
var labels = document.getElementsByTagName("label");
var labelCounter = 0;
while (labelCounter < labels.length) {
labels[labelCounter].innerText = value;
labelCounter++;
}
});
Now you'll see the questions populate with the same possible answer over and over. How do we fix this? Well, first it would pay to get our labels ahead of the loop since the elements themselves aren't being moved or deleted(we're just changing their text property) otherwise we're wasting resources grabbing the same elements over and over again.
Secondly forEach comes with a handy parameter called index that is automatically supplied to the callback function. a.e. forEach(item, indexOFItem) - this means that we can eliminate your while loop entirely and just change the label corresponding to the index of the choice.
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
Edit As pointed out in the comments, you're also going to want to check if the current question exists before loading it. A quick and dirty test for this with your current code is to simply check if the question exists in your object. There are better ways to make sure. You want to avoid static values when it comes to dynamic objects/arrays. As an example the labels issue above where you had set it to check if it was < 5 (less than 5). We changed this to labels.length to dynamically check the length instead of assuming it would always be 5. In the case of the question number, you have 15 questions stated, but that's not dynamic. A better way would be to check against azeem.length if you know that every object within azeem is a question. However, as I'm not sure, a quick fix is the following:
if (azeem[currentQuestion]) {
questions.innerText = azeem[currentQuestion].question;
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
} else {
alert("no more questions");
}
If you change these things the code will run as follows:
$(document).ready(function() {
var azeem = [{
question: "What is Azeem's favourte color?",
choices: ["blue", "yellow", "red", "green"],
answer: 0
}, {
question: "What is Azeem's favourte movie?",
choices: ["Scarface", "The Terminator", "Shawshank Redemption", "The Dark Knight"],
answer: 3
}, {
question: "What was Azeem's first ever job role?",
choices: ["Cleaner", "Store Assistant", "Sales", "Admin"],
answer: 1
}, {
question: "What is Azeem's favourite dish?",
choices: ["Pasta", "Pizza", "Chips", "Curry"],
answer: 0
}, {
question: "What subject did Azeem enjoy the most in school?",
choices: ["Drama", "Science", "P.E", "History"],
answer: 0
}, {
question: "What subject did Azeem least enjoy in school?",
choices: ["Geography", "Maths", "History", "I.T"],
answer: 1
}, {
question: "Which one of these cities has Azeem travelled to?",
choices: ["Madrid", "Lisbon", "Istanbul", "Dublin"],
answer: 1
}, {
question: "Which college did Azeem study in?",
choices: ["NewVic", "Redbridge", "East Ham", "Barking"],
answer: 3
}, {
question: "Who is Azeem's favourite sports icon?",
choices: ["Eric Cantona", "Muhammad Ali", "Cristiano Ronaldo", "Prince Naseem"],
answer: 1
}, {
question: "Who is Azeem's favourite music artist?",
choices: ["Michael Jackson", "Eminem", "Drake", "Linkin Park"],
answer: 1
}, ];
var currentQuestion = 0;
var questionNumberCounter = 1;
var questionNumber = document.getElementById("questionCount");
var choices = document.getElementById("choicesSection");
var questions = document.getElementById("ques");
questions.innerText = azeem[currentQuestion].question;
// The following event listener will transition from the instructions to the first question of the quiz
document.getElementById("startquiz").addEventListener("click", function() {
$(".quiz-intro").fadeOut(600);
$(".quiz-section").delay(600).slideDown("slow");
questionNumber.innerText = questionNumberCounter;
azeem[currentQuestion].choices.forEach(function(value) {
var radio = document.createElement("input");
var label = document.createElement("label");
var div = document.createElement("div");
$(div).addClass("choice");
radio.setAttribute("type", "radio");
radio.setAttribute("name", "answer");
radio.setAttribute("value", value);
var radioID = 'question-' + currentQuestion;
radio.setAttribute('id', radioID);
label.setAttribute("for", radioID);
label.innerHTML = value + "<br>";
choices.appendChild(div);
div.appendChild(radio);
div.appendChild(label);
})
})
document.getElementById("submitanswer").addEventListener("click", function() {
questionNumberCounter++;
questionNumber.innerText = questionNumberCounter;
currentQuestion++;
if (azeem[currentQuestion]) {
questions.innerText = azeem[currentQuestion].question;
var labels = document.getElementsByTagName("label");
azeem[currentQuestion].choices.forEach(function(value, ind) {
labels[ind].innerText = value;
});
} else {
alert("no more questions");
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<h1 class="text-center">FAMILY QUIZ</h1>
<h4 class="text-center">YOU HAVE CHOSEN AZEEM!</h4>
<div class="row text-center quizSection">
<div class="col-md-4 image-section">
<img src="images/3.jpg" id="azeem" class="img-responsive img-thumbnail">
</div>
<div class="col-md-8 quiz-intro">
<h2>INSTRUCTIONS</h2>
<ul id="instructions">
<li>This is a multiple choice quiz</li>
<li>There is only one correct answer per question</li>
<li>At the end of the quiz you will be shown your total score which will reflect the amount of questions answered correctly</li>
<li>There are no hints available during the process of the quiz</li>
<li>Click the 'Start Quiz' button to begin</li>
</ul>
<button id="startquiz" class="btn-small btn-success">START QUIZ</button>
</div>
<div class="col-md-8 quiz-section">
<h5>Question <span id="questionCount">1</span> of 15</h5>
<p class="text-center" id="ques"></p>
<div id="choicesSection">
</div>
<input type="submit" id="submitanswer" value="Submit Answer" class="btn-small btn-success">
</div>
</div>
I'm making a game in JavaScript. The basic idea is to have several buttons that use on.click to perform actions (Fight Monster, Dig for Treasure, etc).
One button loads the next adventure. I have an array containing all the adventures with the values "description" (d), "illustration" (i), and "buttons" (b). The description and illustration HTML show up just fine, but the javascript in the new "Get Flask" button does nothing. Escaping characters doesn't seem to help. Is there a better way to do this?
"Load next adventure" button code: (first couple of lines pick a number randomly up to 5, it has problems that I'll work on next)
<button type="button"
onclick="highLevel = y-1;
while (y >highLevel){ y = Math.round(Math.random() * 5)};
document.getElementById('description').innerHTML = adventure[y].d;
document.getElementById('illustration').innerHTML = adventure[y].i;
document.getElementById('buttons').innerHTML = adventure[y].b"
>Begin</button>
Array code:
adventure[y++]={
d:"Adventure 1",
i:"<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b:"<button type="button" onclick="window.alert('Ye cannot get flask')">Get Flask</button>"
}
For more details, see the code at: https://gist.github.com/janchor/5063f56da41d3e32c825ff154c6bd3be
I didn't change your code much, just fixed what you said :)
function beginClick() {
var highLevel = y - 1;
y = Math.floor(Math.random() * highLevel);
document.getElementById('description').innerHTML = adventure[y].d;
document.getElementById('illustration').innerHTML = adventure[y].i;
document.getElementById('buttons').innerHTML = adventure[y].b
}
var adventure = [];
var y = 0;
adventure[y++] = {
d: "Adventure 1",
i: "<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b: "<button type='button'; onclick='adventure[y].actionGetFlask()'>Get Flask</button>",
actionGetFlask: function() {
alert('Ye cannot get flask');
}
}
<button type="button" onclick="beginClick()">Begin</button>
<div id="description"></div>
<div id="illustration"></div>
<div id="buttons"></div>
Have onclick call a function and move your logic into that.
var adventure = {
d: "Adventure 1",
i: "<img src='cave_entrance.jpg' alt='cave entrance' /><figcaption></figcaption>",
b: "<button type="button" onclick="window.alert('Ye cannot get flask')">Get Flask</button>"
}
function loadHtml() {
document.getElementById('description').innerHTML = adventure.d;
document.getElementById('illustration').innerHTML = adventure.i;
document.getElementById('buttons').innerHTML = adventure.b
}
<button type="button" onclick="loadHtml()">Begin</button>
<div id="description"></div>
<div id="illustration"></div>
<div id="buttons"></div>
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"];
function lengthArray() {
products.length();
document.getElementById("quant").innerHTML = products.length();
}
Hello!
I need some programming a button in javascript that can display the length of the array when the button has been clicked. The code above is my failed attempted to tackle this task, as nothing happens when the said button is clicked.
Edit: Thank you guys for helping me out !
Use products.length instead of products.length() for getting length of array
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"];
function lengthArray() {
document.getElementById("quant").innerHTML = products.length;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
change your code to:
function lengthArray() {
document.getElementById("quant").innerHTML = products.length; <<-- Remove "()"
}
Because length isn't a function. it's a property :)
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
var products = ["Printer", "Tablet", "Router", "Graphics Card","Cooling Fan"];
function lengthArray() {
document.getElementById("quant").innerHTML = products.length;
}
try this:
var products = ["Printer", "Tablet", "Router", "Graphics Card", "Cooling Fan"];
function lengthArray() {
console.log(products.length);
}
<button onclick="lengthArray()">Item Quantity</button>
<p id="quant"></p>
Just remove the brackets after length -
to get the length of an array you have to use length not length()
this is how your code should look like
document.getElementById("quant").innerHTML = products.length;
and add a button to run the function
<button onclick="lengthArray()">Button</button>
or you could just use your paragraph by adding a text to click on
<p id="quant" onclick="lengthArray()">now visible</p>
hope it helps ! ^^
Im trying to create a simple quiz with Javascript. I am struggling to grasp the concept of how to iterate over the values of an array from an object. I eventually want to display a radio button with its value as the choice of answers. If someone could point me in the right direction i would really appreciate it.
Fiddle: http://jsfiddle.net/Renay/eprxgxhu/
Here is my code:
HTML
<h1> General Knowledge Quiz </h1>
<h2 id='questionTitle'> </h2>
<ul id ='selectionList'> </ul>
<p> Click the next button to go to the next question! </p>
<button type="button" id = nextButton> Next </button>
</div>
Javascript
var allQuestions = [{
question: 'What is the capital city of Australia?',
choices: ['Sydney', 'Melbourne', 'Canberra', 'London'],
correctAnswer: 2
},
{
question: 'Who won the 2014 FIFA World Cup?',
choices: ['Brazil', 'England', 'Germany', 'Spain'],
correctAnswer: 2
},
{
question: 'What book series is authored by J.K Rowling?',
choices: ['Game of Thrones', 'Hunger Games', 'Twilight', 'Harry Potter'],
correctAnswer: 3
},
{
question: 'The Eiffel Tower is located in which following country?',
choices: ['Italy', 'France', 'Iceland', 'Mexico'],
correctAnswer: 1
}];
//Reference to tags
var questionTitle = document.getElementById('questionTitle');
var selectionList = document.getElementById('selectionList');
var nextButton = document.getElementById('nextButton');
//Initiating some variables
var i = 0;
var length1 = allQuestions.length;
var correctAnswer = 0;
function populateQuestion() {}
Firstly attach click event to next button and give call to populateQuestion() using counter to iterate through allQuestions array and use i as counter variable.
nextButton.onclick = function() {
/*itterate through questions*/
if(i>allQuestions.length -1){/*go to first when reached last*/
i=0;
}
populateQuestion(i);
i++;
};
Iterate through allQuestions array for question title and choices as:
function populateQuestion(qNum) {
var individualQuestion = allQuestions[i];
questionTitle.innerText = individualQuestion.question;
selectionList.innerHTML = ""; //reset choices list
for(key in individualQuestion.choices){
var radioBtnName = "question"+i+"_choice";
var choiceText = individualQuestion.choices[key];
selectionList.appendChild(createLi(radioBtnName,choiceText));
}
}
Write dynamic li and radio button creation function as:
function createLi(name, choiceText) {
var e = document.createElement('li');
var radioHtml = '<input type="radio" name="' + name + '"';
radioHtml += '/>';
radioHtml += choiceText;
e.innerHTML = radioHtml;
return e;
}
Please refer to this fiddle for same.
You need to associate an onClick event with your button to call the relevant part of the JavaScript. Go through the example here
On another note, using JavaScript for a quiz might not be a good idea as one can see the answers using view-source. I would suggest using PHP to fetch results from a database.