Recently I have been making a math quiz for fun. However, I have tried to come up with a counter to count up the user's correct answers, and display the count at the bottom of the page. I have tried looking up this before but have found nothing.
Here is my HTML:
<div>
<p>What is 18 + 4?</p>
<div>
<input type="text" id="lol">
<button id="q1" onclick="lmao()">Answer</button>
</div>
<p id="q1c" class="correct"></p>
<p id="q1i" class="incorrect"></p>
<p>What is 19 + 21?</p>
<div>
<input type="text" id="loll">
<button id="q2" onclick="lmfao()">Answer</button>
</div>
<p id="q2c" class="correct"></p>
<p id="q2i" class="incorrect"></p>
</div>
Here is my JavaScript:
function lmao() {
if (document.getElementById("lol").value == "22") {
document.getElementById("q1c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q1i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
function lmfao() {
if (document.getElementById("loll").value == "40") {
document.getElementById("q2c").innerHTML = "Correct!";
alert('Correct');
} else {
document.getElementById("q2i").innerHTML = "Incorrect!";
alert('Incorrect');
}
}
Instead of using separate <p> tags for marking if the answers are incorrect or correct, you can simplify it down to one <p> tag with different id's, and just update the text inside them, and then we use the simple JavaScript notation to update the color of the font: object.style.color = "green". This provides much cleaner HTML.
Here is a working example (I stripped out all the excess tags and styles):
var answer1Count = 0;
var answer2Count = 0;
var correctCount = 0;
function answer1() {
var answer = document.getElementById("problem1");
var alert = document.getElementById("problem1Alert");
if (answer.value == "22") {
alert.textContent = "Correct!";
alert.style.color = "green";
correctCount +=1; //update global count of correct answers
answer1Count +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer1Count !== 0) {
answer1Count -=1;
correctCount -=1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
function answer2() {
var answer = document.getElementById("problem2");
var alert = document.getElementById("problem2Alert");
if (answer.value == "40") {
alert.textContent = "Correct!";
alert.style.color = "green";
answer2Count +=1; //update global count of correct answers
correctCount +=1;
document.getElementById("correctCount").textContent = correctCount;
} else {
if (answer2Count !== 0) {
answer2Count -=1;
correctCount -= 1;
document.getElementById("correctCount").textContent = correctCount;
}
alert.textContent = "Incorrect!";
alert.style.color = "Red";
}
}
<p>What is 18 + 4?</p>
<input type="text" id="problem1">
<button onclick="answer1()">Answer</button>
<p id="problem1Alert"></p>
<p>What is 19 + 21?</p>
<input type="text" id="problem2">
<button onclick="answer2()">Answer</button>
<p id="problem2Alert"></p>
<p>Correct Answer Count: <b id="correctCount">0</b></p>
Instead of using innerHTML, we use textContent it is safer and faster for updating with pure text because it does not have to parse for HTML. You can easily search around SO for the disadvantages of using innerHTML.
In addition, I would avoid inline styling with CSS at all costs. It makes your code much harder to read. I recommend putting all your styles in a separate stylesheet and just including that style sheet inside your <head> tag like so:
<link rel="stylesheet" href="style.css">
Related
The program needs to take the input of a free response question. the answer being poseidon. When the incorrect answer is put in the program responds with incorrect and turns red. My goal is when poseidon is typed in it will turn green and say correct, but it doesn't react at all to the correct answer.
I've tried a few different variat and this is as close as I can get
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght#500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
document.addEventListener('DOMContentLoaded', function(){
let incorrect = document.querySelectorAll(".incorrect");
let correct = document.querySelector("#correct");
let response = document.querySelector("#response");
correct.addEventListener('click', function(){
correct.style.backgroundColor = "green";
response.innerHTML = "Correct";
})
for (let x = 0; x < incorrect.length; x++)
{
incorrect[x].addEventListener('click', function() {
incorrect[x].style.backgroundColor = 'red';
response.innerHTML = "incorrect";
})
}
document.querySelector("#submit").addEventListener('click', function(){
let input = document.querySelector('input');
let reply = document.querySelector("#reply");
if (input.value === "poseidon")
{
intput.style.color = 'green';
reply.innerHTML = "correct";
}
else
{
input.style.color = "red";
reply.innerHTML = "incorrect";
}
});
});
</script>
</head>
<body>
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>What is the capital of New York?</h3>
<button class="incorrect">Manhattan</button>
<button class="incorrect">Bronx</button>
<button id="correct">Albany</button>
<p id="response"></p>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>Who was the first god killed in the game title God of War III</h3>
<input type="text">
<button id="submit">Submit</button>
<p id="reply"></p>
</div>
</div>
</body>
</html>
You misspelled input : intput.style.color = 'green';
Common error, don't worry it was hard to find. ;)
So, just change :
if (input.value === "poseidon")
{
intput.style.color = 'green';
reply.innerHTML = "correct";
}
else
{
input.style.color = "red";
reply.innerHTML = "incorrect";
}
to
if (input.value === "poseidon")
{
input.style.color = 'green';
reply.innerHTML = "correct";
}
else
{
input.style.color = "red";
reply.innerHTML = "incorrect";
}
Also consider that user may type "Poseidon", so I suggest you to check the value as this :
if (input.value.toLowerCase() === "poseidon")
I am practicing with JavaScript Array function. What I want to achieve is to show google embedded images inside the display section when the user clicks "Show my grocery list" button after entering "banana", else the texts will be shown instead.
These are my codes.
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup",function(ev){
if(ev.keyCode == 13){
groceryList.push(grocery.value);
console.log("array",groceryList);
}
});
showItems.addEventListener("click",function(){
for (var i = 0; i < groceryList.length;i++){
if(groceryList[i] == "banana"){
display.src = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
#display {
width:100px;
height:100px;
}
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery"/>
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
It is currently not showing anything. I have a feeling that I have written a wrong syntax inside the loop function? I would appreciate a solution and tips. Thank you.
You've to remove the keyCode=13 condition first and then need to create an img element with src of image based on condition (groceryList[i] == "banana") to display the image inside the <div> element, For example:
var grocery = document.getElementById("grocery");
let showItems = document.getElementById("showItems");
const display = document.getElementById("display");
var groceryList = [];
grocery.addEventListener("keyup", function(ev) {
//if(ev.keyCode == 13){
groceryList.push(grocery.value);
//console.log("array",groceryList);
//}
});
showItems.addEventListener("click", function() {
for (var i = 0; i < groceryList.length; i++) {
if (groceryList[i] == "banana") {
var source = "https://i5.walmartimages.ca/images/Enlarge/271/747/6000191271747.jpg";
var img = document.createElement("IMG"); //create img element
img.src = source; //set img src
display.appendChild(img); // display image inside <div>
} else {
display.innerHTML += groceryList[i] + "<br/>";
}
}
});
<div id="controls">
<input type="text" placeholder="grocery items" id="grocery" />
<button id="showItems">Show My Grocery List</button>
</div>
<div id="display"></div>
I need Happy Birthday to display only after a user puts the right input in prompt (which is 30). I want it to be hidden by default.
The reason I am doing it this way is that I want to add some CSS animation to this h1 tag later.
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday"> Happy Birthday! </h2>
You need to add hidden attribute to element with id = "bday"
document.getElementById("bday").style.display = "none";
function myFunction() {
var txt;
var myTextbox = document.getElementById("bday");
var Age = prompt("How old are you?:");
if (Age == 30) {
document.getElementById("bday").style.display = "block";
return myTextbox;
} else {
txt = "Really? ";
}
document.getElementById("demo").innerHTML = txt;
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="demo"></h1>
<h2 id="bday" hidden> Happy Birthday! </h2>
No need to complicate, you can do it with less markup and improved functionality:
function myFunction() {
var myTextbox = document.getElementById("response");
var Age = prompt("How old are you?");
if (Age == 30) {
myTextbox.innerHTML = "Happy Birthday!";
} else if (Age == null) { // addition, if clicked on cancel
myTextbox.innerHTML = "";
} else {
myTextbox.innerHTML = "Really?";
}
}
<button onclick="myFunction()">HOW OLD ARE YOU?</button>
<h1 id="response"></h1>
So I have been racking my brain on how to add the a different value from the text box to a different div. So div1 gets the first thing the user typed, div2 gets the second, div3 gets the third, and so on. Everytime a user presses the "Add" button whatever the user typed will be added to one of the Div's above it. Right now I have it to where by pressing "Add" the value of the textbox is put in the first div. How do I create a function that will allow the user to add values to other divs. I assume you need a for loop but I do not know how to tackle it.
Here is my code:
<html>
<head>
<link rel="stylesheet" type="text/css" href="newTicket2.0.css">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<div id="colorme" style = "cursor:pointer" onClick= "highlightLink()"><p id = "doubleStuff" ondblclick = "dubleStuff()">check this out</p></div>
<div id="colorme2" style = "cursor:pointer" onClick= "highlightLink2()"><p id = "doubleStuff2" ondblclick = "dubleStuff2()">check this out</p></div>
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick = "workInfoAdd()">Add</button>
<script>
function highlightLink(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'red';
highL2.style.backgroundColor = 'transparent';
};
function highlightLink2(){
var highL = document.getElementById('colorme');
var highL2 = document.getElementById('colorme2');
highL.style.backgroundColor = 'transparent';
highL2.style.backgroundColor = 'red';
};
function dubleStuff(){
var x = "You double clicked it";
document.getElementById('putstuff').innerHTML = x;
};
function dubleStuff2(){
var x = "different stuff";
document.getElementById('putstuff').innerHTML = x;
};
function workInfoAdd(){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {
z.value = "";
}
};
</script>
</body>
</html>
Would something like this work.
var i = document.getElementById('addingInfo');
for(i = 0; i < 4; i++){
document.getElementbyId('workInfo').value = i //or some other variable that specifies the "adding info"
Any assistance would be greatly appreciated. As stated above after everytime the user presses ADD, the value they put into the text box will be added to the subsequent div. First add goes to first div, second goes to second div and so on.
You should probably write something like this:
var divIndex = 0;
function workInfoAdd() {
var z = document.getElementById('workInfo');
var p = document.getElementById('addingInfo' + (divIndex || ''));
if (!p) {
return;
}
if (z.value === null || z.value === "") {
alert('please enter work info');
} else {
p.innerHTML = z.value;
z.value = "";
}
divIndex++;
};
<div id="workInfo1" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo"></p>
</div>
<div id="workInfo12" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo1"></p>
</div>
<div id="workInfo13" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo2"></p>
</div>
<div id="workInfo14" style="cursor:pointer;border: dotted 1px">
<p id="addingInfo3"></p>
</div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type="button" name="addWorkInfo" id="addWorkInfo" onclick="workInfoAdd()">Add</button>
Additionally you can use document.querySelector() for more advanced matching of elements ex.
var p = document.querySelector('.workInfo' + divIndex + ' > p.addingInfo' + divIndex);
Try the below code but remember that this solution should be used if you are going to limit the number of div (i.e only 3 or 4 divs) because if you want unlimited divs you will have to program an if-else statement for each possible div:
// Declare variable
var x = 0;
function workInfoAdd(){
// Increment
x++
// Check increment value
if(x == 1){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else { z.value = "";}
}
// Check increment value
else if(x == 2){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo1').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
// Check increment value
else if(x == 3){
var z = document.getElementById('workInfo')
document.getElementById('addingInfo2').innerHTML = z.value
if (z.value === null || z.value === ""){
alert('please enter work info');
}
else {z.value = "";}
}
}
https://jsfiddle.net/6byvuzxf/
I have created check points as mentioned in my comment before.
Hope this helps.
See if this is what you want. I have added a class for all the p tags which will contain the information after click.
Html
<p id = "putstuff"></p>
<br>
<br>
<br>
<br>
<div id = "workInfo1" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo"></p> </div>
<div id = "workInfo12" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo1"></p> </div>
<div id = "workInfo13" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo2"></p></div>
<div id = "workInfo14" style = "cursor:pointer"><p class ="addingInfo" id = "addingInfo3"></p></div>
<br>
<br>
<textarea name="workInfo" cols="60" rows="5" id="workInfo">
</textarea>
<button type = "button" name = "addWorkInfo" id = "addWorkInfo" onclick ="workInfoAdd()">Add</button>
javascript
function workInfoAdd()
{
var elements = document.getElementsByClassName('addingInfo');
for(i=0;i<elements.length;i++)
{
if(elements[i].innerHTML == "")
{
elements[i].innerHTML = document.getElementById('workInfo').value;
document.getElementById('workInfo').value = "";
return;
}
}
}
http://jsfiddle.net/okLme061/1/
I am new to coding and I have completed Codecademy's HTML, CSS and Javascript courses, and now I am making a very simple game.
I am trying to add 5 to my variable score, but I don't know how! I can use ++score to add 1, but I don't know how to add 5.
My simplified code for adding 1 is:
<html>
<head>
<title>Webpage</title>
<script>
var score = 0;
function add1() {
alert("Adding +1 to your score!");
++score;
alert(score);
};
</script>
</head>
<body>
<button onclick="add1()";> Add One </button>
</body>
</html>
shortest / easiest + 5 in Javascript
score += 5;
add + 5 to the score and set that as the score
score = score + 5;
function add1() {
alert("Adding +5 to your score!");
score = score + 5;
alert(score);
};
You can add this in.It's like the web storage Api if you disable the alert.Learn more
var score = 0;
document.getElementById("boy").innerHTML = +score;
function correct() {
alert("And that is correct!")
++score;
document.getElementById("boy").innerHTML = +score;
return true;
}
function wrong() {
alert("And that is wrong!")
return false;
}
var times = 0;
document.getElementById("hey").innerHTML = +score;
function yourname() {
++times;
document.getElementById("hey").innerHTML = +times;
}
<p>
Score:<span id="boy"></span>
</p>
<h2>Is javascript powerful?</h2>
<button onclick='correct()'>Yes</button>
<button onclick='wrong()'>No</button>
<h2>If you went into the w3schools link.This feels familar.</h2>
<p>
You have clicked the button:<span id="hey"></span> times
</p>
<button onclick="yourname()">Click me!!!</button>
You maybe will not see the snippet.
Javascript:
var score = 0;
document.getElementById("boy").innerHTML = +score;
function correct() {
alert("And that is correct!")
++score;
document.getElementById("boy").innerHTML = +score;
return true;
}
function wrong() {
alert("And that is wrong!")
return false;
}
var times = 0;
document.getElementById("hey").innerHTML = +score;
function yourname() {
++times;
document.getElementById("hey").innerHTML = +times;
}
Html:
<p>
Score:<span id="boy"></span>
</p>
<h2>Is javascript powerful?</h2>
<button onclick='correct()'>Yes</button>
<button onclick='wrong()'>No</button>
<h2>If you went into the w3schools link.This feels familar.</h2>
<p>
You have clicked the button:<span id="hey"></span> times
</p>
<button onclick="yourname()">Click me!!!</button>