I have developing a quiz app in JavaScript and the problem is the questions are not iterating through. In other words, after a user takes the first question by clicking a multiple choice answer and then clicking next button, it does not go to the next question, simultaneously, JS does not recognize I answered the question via Answer the question! being the only output from the if conditional.
$(function (){
startQuiz();
answerResponse();
answerSubmitted();
renderQuestionPage();
});
const data = {
questions:[
// this is object 1 but we won't name it because it is inside an array
{
question: 'Question 1 what is that thing?',
answers:[
'this 1',
'that 2',
'something 3',
'allodat 4'
],
correctAnswer: 'allodat 4'
},
// this is object 2 but we won't name it because it is inside an array
{
question: 'Question 2 what is that other thing?',
answers: [
'bloop',
'dope',
'FIRE',
'HOTZ'
],
correctAnswer: 'dope'
}
],
currentQuestionIndex: 0,
totalScore: 0,
startedQuiz: false,
};
function resetQuiz(){
data.totalScore = 0;
data.currentQuestionIndex = 0;
}
function renderQuestionPage() {
var currentQuestionObj = data.questions[data.currentQuestionIndex];
renderQuestion();
renderQuestionOptions(currentQuestionObj.answers);
}
function renderQuestion() {
var progressHTML = "<span>(" + (data.currentQuestionIndex + 1) + '/' + data.questions.length + ")</span>"
var questionText = data.questions[data.currentQuestionIndex].question;
$(".js-question-text").html(progressHTML + questionText);
console.log(renderQuestion);
}
function renderQuestionOptions(answers){
$(".myForm label").each(function(index, label) {
$(this).find("input").attr("value", answers[index]);
$(this).find("input").prop("checked", false);
$(this).find("span").text(answers[index]);
});
}
function finalResults(){
$("#questionPage").addClass("hidden");
$("#results-page").removeClass("hidden");
$('#retake-button').removeClass("hidden");
var element = $('.js-final-results');
element.html("<h2>" + "You got" + '' + data.correctChoice + ' ' + "out of" + ' ' + data.questions.length + ' ' + "correct" + "</h2>");
retakeQuiz();
}
function checkAnswer(userChoice) {
var correctChoice = data.questions[data.currentQuestionIndex].correctAnswer;
console.log(data.currentQuestionIndex, data.questions[data.currentQuestionIndex]);
if (userChoice === correctChoice) {
data.totalScore++;
renderQuestionFeedback(true);
data.currentQuestionIndex++;
} else if (userChoice === undefined) {
renderQuestionFeedback("unanswered");
} else {
renderQuestionFeedback(false);
data.currentQuestionIndex++;
}
if (data.currentQuestionIndex == data.questions.length) {
finalResults();
} else {
renderQuestionPage();
}
}
function renderQuestionFeedback(response){
var feedback = $(".popup-inner");
if (response === true) {
feedback.find("h2").text("That was correct");
} else if (response === false) {
feedback.find("h2").text("That was incorrect");
} else if (response === "unanswered") {
feedback.find("h2").text("Answer the question!");
}
}
function startQuiz(){
$("#startQuiz").click(function(e){
$("#questionPage").removeClass("hidden");
$("#startQuiz").addClass("hidden");
console.log("take quiz clicked");
});
}
function retakeQuiz(){
$("#retake-button").click(function(e){
$("#questionPage").removeClass("hidden");
$("#retake-button").addClass("hidden");
resetQuiz();
renderQuestionPage();
});
}
function answerSubmitted(){
$("#submit-answer").click(function(e){
e.preventDefault();
var userChoice = $("input[name='answerChoice']:checked").val();
renderQuestionFeedback()
checkAnswer(userChoice);
});
}
function answerResponse(){
$("#submit-answer").on("click", function(e){
e.preventDefault();
var targetPopupClass = $(this).attr("data-popup-open");
$(`[data-popup="' + targetPopupClass + '"]`).fadeIn(250);
e.preventDefault();
renderQuestionFeedback();
});
}
function resetQuiz(){
data.totalScore = 0;
data.currentQuestionIndex = 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Brian's Quiz</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="quizstyle.css">
</head>
<body>
<header id="title" role="banner">
<h1>Brian's Quiz</h1>
</header>
<div id="container">
<section id="startPage" role="region">
<h2>Thinkful is in da House!</h2>
<button type="submit" id="startQuiz" role="button">Start Quiz</button>
</section>
<section id="results-page" class="hidden">
<div class="js-final-results text-center"></div>
<button class="hidden" id="retake-question"></button>
</section>
<section class="popup" data-popup="popup-feedback">
<div class="popup-inner">
<h2 id="text-feedback"></h2>
</div>
</section>
<section id="questionPage" role="region">
<h3 class="js-question-text">
<span>(1/10)</span>
</h3>
<form class="myForm" action="form" role="form">
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<label class="answer">
<input type="radio" name="answerResponse">
</label>
<button type="submit" id="submit-answer" data-popup-open="popup-feedback">Next</button>
<p><span id="questionNo">5</span> out of <span id="outOf">10</span></p>
</form>
</section>
<section id="showAnswer" role="region">
<h2>Correct</h2>
<button type="submit" id="continue" role="button">Continue Quiz</button>
</section>
<section id="finalPage" role="region">
<h2>Your Result</h2>
<p>You got <span id="correctNo">5</span> out of <span id="total-outof">10</span> correct</p>
<button type="submit" id="retake-button">Retake Quiz</button>
</section>
</div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="quizJS.js" type="text/javascript"></script>
</html>
In the console, when I click the next button, I just get the same question object or question number 1 over and over.
You will find that something is wrong when you compare these lines of code:
<input type="radio" name="answerResponse">
and
function answerSubmitted(){
$("#submit-answer").click(function(e){
e.preventDefault();
var userChoice = $("input[name='answerChoice']:checked").val();
renderQuestionFeedback()
checkAnswer(userChoice);
});
}
Either your input name='answerResponse' or input name='answerChoice'
Give it a try.
Related
I'm trying to build an interactive text with Javascript. I can do it by using a new function each element I create, but if I do that I'll have too many functions.
Could somebody tell me what is wrong with the following code and what I should do so it works?
Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1(peter)">Peter</button>
<button id="paul" onclick="includeName1(paul)">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2(mary)">Mary</button>
<button id="emma" onclick="includeName2(emma)">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").innerHTML;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
You need to wrap the names in apostrophes, at the moment you're trying to pass an object called 'peter' to the function. On the input, you need to use value instead of innerHtml.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1('peter')">Peter</button>
<button id="paul" onclick="includeName1('paul')">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2('mary')">Mary</button>
<button id="emma" onclick="includeName2('emma')">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").value;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
For the record...
this code should be more readable on this way:
const inTexts = document.getElementById('interractiv-texts')
, outText = document.getElementById('Out-Text')
, tVals = { man: '', wife: '', years: '' }
;
const setText = e =>
{
if (!e.target.matches('[data-part]')) return
tVals[e.target.dataset.part] = e.target.value
outText.textContent = `My name is ${tVals.man}, I'm married to ${tVals.wife}. We've been married for ${tVals.years} years.`
}
inTexts.oninput = setText
inTexts.onclick = setText
<div id="interractiv-texts">
<p>Name:</p>
<select data-part="man">
<option value="Peter">Peter</option>
<option value="Paul">Paul</option>
<option value="John">John</option>
</select>
<p>Wife's name</p>
<button value="Mary" data-part="wife">Mary</button>
<button value="Emma" data-part="wife">Emma</button>
<p>How long have you been married?</p>
<input data-part="years" type="number" >
</div>
<p id="Out-Text"></p>
I'm trying to validate the radio buttons so that an error pops up when it's not checked.
However the error won't disappear unless I select an option from the Question 2 set and nothing from Question 1.
I'm trying to have both messages pop up for both questions if unchecked and and individually disappear when something is selected for that question
//Javascript
var answers = ["A","C"],
total = answers.length;
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpan = document.getElementById("choice_error");
var isChecked = false;
errorSpan.innerHTML = "";
for (var y = 0; y < radios.length; y++)
{
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpan.innerHTML = "Please select a choice.";
}
}
return isChecked;
}
function getScore()
{
var score = 0;
for (var i = 0; i < total; i++)
{
document.getElementById("flag"+i).innerHTML = "";
if(getCheckedValue("choice"+i) == answers[i])
{
score += 1;
document.getElementById("flag"+i).innerHTML = "Your answer is correct.";
}
else if(getCheckedValue("choice"+i) != answers[i])
{
document.getElementById("flag"+i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore()
{
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header><h1>Disney Quiz</h1></header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last"value=""><br>
<section id="radio1">
<p> Question 1) What was Walt Disney's first character he created? <span id="choice_error"></span></p>
<input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit<br>
<input type="radio" name="choice0" value="B">Donald Duck<br>
<input type="radio" name="choice0" value="C">Mickey Mouse<br>
<input type="radio" name="choice0" value="D">Goofy<br>
<p id="flag0"></p>
</section>
<section id="radio2">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span id="choice_error"></span></p></p>
<input type="radio" name="choice1" value="A">Movie<br>
<input type="radio" name="choice1" value="B">Live-Action<br>
<input type="radio" name="choice1" value="C">Cel-animated Film<br>
<input type="radio" name="choice1" value="D">Cartoon<br>
<p id="flag1"><p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer> <p align="center"> Project 4 - Fall 2018 </p> </footer>
</body>
</html>
fastest method:
HTML:
<span id="choice_error_choice0"></span>
<!-- ... -->
<span id="choice_error_choice1"></span>
JS:
function getCheckedValue(radioName)
{
let isChecked = true;
let exist = document.querySelector(`input[name='${radioName}']:checked`);
let choice_error = document.getElementById('choice_error_'+radioName);
choice_error.innerHTML = "";
if (exist == null)
{
isChecked = false;
choice_error.innerHTML = "Please select a choice.";
}
return isChecked;
}
In your code both error spans have the same ID "choice_error". No two html elements should have the same id, as then the browser won't be able to differentiate them.
If you want to access both error span elements, you can give each of them a ccs class "choice_error" and call the method document.getElementsByClassName().
Also you need to clear the error span inside the loop
function getCheckedValue(radioName)
{
var radios = document.getElementsByName(radioName);
var errorSpans = document.getElementsByClassName("choise_error");
var isChecked = false;
for (var y = 0; y < radios.length; y++)
{
errorSpans[y].innerHTML= ""; // clear the span
if(radios[y].checked)
{
isChecked = true;
return radios[y].value
}
else if(!radios[y].checked)
{
isChecked = false;
errorSpans[y].innerHTML = "Please select a choice."; // error message
}
}
return isChecked;
}
I've tidied a couple of things up. Using label for a start.
The main difference is I now use a parent question id to group our answers and change to class for choice_error.
Then I've use document.querySelector to find the checked answer and set the child error messages display style.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function getAnswer(QuestionId) {
//Get the selected answer radio button
var answer = document.querySelector("#" + QuestionId + " input[type=radio]:checked");
//It there isn't one
if (answer === null) {
//show the error mesage
document.querySelector("#" + QuestionId + " .choice_error").style.display = "inline";
} else {
//Otherwise hide the message
document.querySelector("#" + QuestionId + " .choice_error").style.display = "";
//And set the answer value
answer = answer.value;
}
return answer;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
document.getElementById("flag" + i).innerHTML = "";
if (getAnswer("radio" + (i + 1)) == answers[i]) {
score += 1;
document.getElementById("flag" + i).innerHTML = "Your answer is correct.";
}
/*No need to check again, it either matches or doesn't*/
else {
document.getElementById("flag" + i).innerHTML = "Your answer is incorrect.";
}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
We could refactor this some more, let one method handle manipulating the question related actions.
//Javascript
var answers = ["A", "C"],
total = answers.length;
function checkAnswer(QuestionId, Answer) {
var isCorrect = false;
var questionElement = document.getElementById(QuestionId);
//Get the selected answer radio button
var answerElement = questionElement.querySelector("input[type=radio]:checked");
//It there isn't one
if (answerElement === null) {
//show the error mesage
questionElement.querySelector(".choice_error").style.display = "inline";
questionElement.querySelector("[id^=flag]").innerHTML = "";
} else {
//Otherwise hide the message
questionElement.querySelector(".choice_error").style.display = "";
//And chcek answer
isCorrect = Answer == answerElement.value;
questionElement.querySelector("[id^=flag]").innerHTML = "Your answer is " + (isCorrect ? "correct" : "incorrect");
}
return isCorrect;
}
function getScore() {
var score = 0;
for (var i = 0; i < total; i++) {
if(checkAnswer("radio" + (i + 1), answers[i])) {
score++;}
}
return score;
}
function returnScore() {
var x = document.getElementById("myText").value;
document.getElementById("results").innerHTML = x + ", your score is " + getScore() + "/" + total;
}
.questions label {
display: block;
}
.choice_error {
color: red;
display: none;
}
<!--HTML -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>Disney Quiz</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" href="images/favicon.ico">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script src="scripts/quiz.js"></script>
</head>
<body>
<header>
<h1>Disney Quiz</h1>
</header>
<main>
<p>Click on the correct answer for each question and submit your results.</p>
<form>
<fieldset>
<legend>Trivia Questions</legend>
<label> Enter your Name</label> <input type="text" id="myText" name="fieldName" placeholder="First Last" value=""><br>
<section id="radio1" class="questions">
<p> Question 1) What was Walt Disney's first character he created? <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice0" value="A">Oswald the Lucky Rabbit</label>
<label><input type="radio" name="choice0" value="B">Donald Duck</label>
<label><input type="radio" name="choice0" value="C">Mickey Mouse</label>
<label><input type="radio" name="choice0" value="D">Goofy</label>
<p id="flag0"></p>
</section>
<section id="radio2" class="questions">
<p> Question 2) Snow White was the first ____ to ever be produced successfully. <span class="choice_error">Please select a choice</span></p>
<label><input type="radio" name="choice1" value="A">Movie</label>
<label><input type="radio" name="choice1" value="B">Live-Action</label>
<label><input type="radio" name="choice1" value="C">Cel-animated Film</label>
<label><input type="radio" name="choice1" value="D">Cartoon</label>
<p id="flag1">
<p>
</section>
<br>
<input type="button" onclick="returnScore()" value="Show Results">
<input type="button" onclick="window.location.href = 'index.html';" value="Review">
<p id="results"></p>
</fieldset>
</form>
</main>
<aside>
</aside>
<footer>
<p align="center"> Project 4 - Fall 2018 </p>
</footer>
</body>
</html>
I'm trying to make a quiz, here is the html :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>English Test</title>
<link rel="stylesheet" href="testCss.css">
</head>
<body>
<br>
<div style="font-size:20px">
<p>Please choose the correct answer and at the end tap the score button. </p>
<br>
<div>
2. I
<select id="question2">
<option value="_">_</option>
<option value="Am">am</option>
<option value="Is">is</option>
<option value="Are">are</option>
</select>
22 years old.
<span id="question2_answer"></span>
</div>
<br>
<br>
<div>
101. When can we meet again?
<span id="question101_answer"></span>
<div>
<input type="radio" name="question101" > When are you free?<br>
<input type="radio" name="question101" > It was two days ago. <br>
<input type="radio" name="question101" > Can you help me?
</div>
</div>
<br>
<br>
<div>
8. What is your father like?
<span id="question8_answer"></span>
<div>
<input type="radio" name="question8" > He likes listenning to music.<br>
<input type="radio" name="question8" > He likes to play football. <br>
<input type="radio" name="question8" > He is friendly.<br>
<input type="radio" name="question8" > He has a car.
</div>
</div>
<br>
<br>
<button id="button1" class="button" onclick="viewScore()">Score Result</button>
<br>
<input type="text" id="grade1" value="" readonly>
<br>
<script src="testJs.js"></script>
and here is the testJs.js that i used:
var score = 0;
function viewScore() {
var answer2 = document.getElementById("question2").value;
var answer8 = document.getElementsByName("question8");
var answer101 = document.getElementsByName("question101").value;
if (answer2 == "Am") {
document.getElementById("question2_answer").style.color = "green";
document.getElementById("question2_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question2_answer").style.color = "red";
document.getElementById("question2_answer").innerHTML = "✖ Wrong!";
}
if (answer8[2].checked) {
document.getElementById("question8_answer").style.color = "green";
document.getElementById("question8_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question8_answer").style.color = "red";
document.getElementById("question8_answer").innerHTML = "✖ Wrong!";
}
if (answer101[0].checked) {
document.
getElementsById("question101_answer").style.color = "green";
document.getElementsById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementsByID("question101_answer").style.color = "red";
document.getElementsByID("question101_answer").innerHTML = "✖ Wrong!";
}
if (score<=5) {
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Elementary.";
} else if(score<=8){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Pre Intermediate.";
}else if(score<=15){
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Intermediate.";
}else{
document.getElementById("grade1").value = " Your total score is: "+ score+" Your level is: "+"Upper Intermediate.";
}
console.log(score);
score = 0;
}
However, I'm getting following error on question 101. I check it several times and I have no idea where does this error coming from ! It refers to question 101 and mentions cannot read property '0' of undefined.
Thanks for any help in advance.
testJs.js:26 Uncaught TypeError: Cannot read property '0' of undefined
at viewScore (testJs.js:26)
at HTMLButtonElement.onclick (testHTML.html:57)
This is happening because in this line:
var answer101 = document.getElementsByName("question101").value;
you are putting the value of the input (which is NULL or UNDEFINED because the HTMLCollection returned by getElementsByName (note the plural) doesn't have a value property) into the var answer101 and NOT the input itself.
To fix this, change the above line to:
var answer101 = document.getElementsByName("question101");
You have to select array (not value) for var answer101
var answer101 = document.getElementsByName("question101");
And correct if content for answer101
if (answer101[0].checked) {
document.getElementById("question101_answer").style.color = "green";
document.getElementById("question101_answer").innerHTML = "✔";
score += 1;
} else {
document.getElementById("question101_answer").style.color = "red";
document.getElementById("question101_answer").innerHTML = "✖ Wrong!";
}
I am trying to make a simple guessing number game. I cannot get the function to operate correctly, or display my messages to the user. Am I not using the innerHTML correctly? I also want the game to reload when the number is guessed correctly, I am not sure if it works because the game will not operate.
var number = 0;
var output = document.getElementById("output").innerHTML;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
function checkGuess() {
"use strict";
var guess = document.getElementById("guess").value;
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number); {
output = "The number I am thinking of is higher than" + guess;
} else if (guess > number); {
output = "The number I am thinking of is lower than" + guess;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
<link rel="stylesheet" href="css/Lab6.css" />
<script type="text/javascript" src="script/Lab6.js"></script>
</head>
<body onload="pickInteger()">
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="button" name="mybutton" value=" Guess " onclick="checkGuess()">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
you had a semicolon if (guess < number); and else if (guess > number); which is wrong just remove it and it will start working, see below your code
var number = 0;
var output = document.getElementById("output").innerHTML;
var consolecounter = 0;
function pickInteger() {
"use strict";
number = Math.floor(Math.random() * 10 + 1);
}
$(document).ready(function() {
pickInteger();
$("form[name='AForm']").on('submit', function(e) {
"use strict";
e.preventDefault();
var guess = parseInt(document.getElementById("guess").value);
if (guess == number) {
alert(number + " " + "Is the correct number!");
output = "";
pickInteger();
}
if (guess < number) {
console.log("The number I am thinking of is higher than " + guess);
consolecounter++;
} else if (guess > number) {
console.log("The number I am thinking of is lower than " + guess);
consolecounter++;
}
clearConsole(consolecounter);
})
})
function clearConsole(consolecounter) {
(consolecounter == 3) && (setTimeout(function() {
console.clear();
consolecounter = 0;
}, 2000));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>Guess the Number</title>
</head>
<body>
<div>
<h2><strong>Guess the Number</strong></h2>
</div>
<br/>
<div id="formDiv">
<form name="AForm" method="get">
<p>The computer has picked a number between 1 - 99, you must choose the correct number to win the game. When you guess the right number the game will restart.<br/>
</p>
<div id="bodyDiv">
<p> Your guess is:
<input id="guess" type="text" size="1" name="theData" value="" autofocus/>
<input type="submit" name="mybutton" value=" Guess ">
</p>
<p id="output">
</p>
</div>
</form>
</div>
</body>
</html>
how would I remove a list item from my to do list onclick! And how would i set up a counter to add and display how many tasks i have and how many left once one is deleted.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
</body>
</html>
JavaScript
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete'>clear</button></li>";
}
}
Add an onclick event to clear button and call the function clearItem() that deletes the item.
For your second question,
And how would i set up a counter to add and display how many tasks i
have and how many left once one is deleted.
Add a variable total_added that increment when the user adds an item, and another variable remaining that decrement when the user clears an item.
var total_added = 0; //initialize the var to zero
var remaining = 0; //initialize the var to zero
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
}
else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='clearItem()'>clear</button></li>";
total_added++;
remaining++; //increment total_added and remaining when user adds an item
document.getElementById('total_added').innerHTML = "Total number of tasks added = " + total_added;
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
}
function clearItem() {
event.currentTarget.parentElement.remove();
remaining--; //decrement remaining when user clears an item
document.getElementById('remaining').innerHTML = "Number of tasks remaining = " + remaining;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Task 1</title>
<link rel="stylesheet" href="styles.css" type="text/css">
<script src="script.js"></script>
</head>
<body>
<div id="container">
<h1>My To Do List</h1>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()" > Add Task</button>
</div>
<ul id="todo_list"></ul>
<p id="total_added">Total number of tasks added = 0</p>
<p id="remaining">Number of tasks remaining = 0</p>
</body>
</html>
I think counter of the list is unnecessary. You could always count childNode in your todo_list for the left todo list. But counter for deleted list is still useful.
var list_now = document.getElementById('todo_list').childNodes.length;
Add the removeTask() function in the onClick event of the delete button and add the removeTask function.
Like this :
JS :
function addtask() {
var input = document.getElementById('input_field').value;
if (input == "") {
window.alert("You must enter a value in the New Task field.");
} else {
var noteList = document.getElementById('todo_list');
noteList.innerHTML += "<li>" + input + "<button id='delete' onclick='removeTask()' >clear</button></li>";
countItems();
}
}
function removeTask() {
event.currentTarget.parentElement.remove();
countItems();
}
function countItems() {
var count = document.querySelectorAll("#todo_list > li").length;
document.getElementById("count").innerHTML = count + ' item(s)';
}
HTML :
<div id="container">
<h1 id="title">My To Do List</h1>
<p id="count"></p>
<input type="text" id="input_field" name="input_field" placeholder="Enter New Task" required>
<button type="button" id="add" onclick="addtask()"> Add Task</button>
</div>
<ul id="todo_list"></ul>
CodePen