Having Trouble With JavaScript Location Reload - javascript

I'm creating my first JavaScript calculator, and I thought I could cheat on the clear button by reloading the page, but it doesn't seem to work. I have tried online editors, reopening chrome, moving files, and it still doesn't seem to work I don't know why, but help would be greatly appreciated.
EDIT: Sorry for taking so long, as you can see I now have the HTML and CSS to go with the JavaScript
var firstNumber = [];
var secondNumber = [];
let current = 'firstNumber';
var operation;
function clear(){
location.reload();
}
function set(number){
if (current == 'firstNumber'){
firstNumber.push(number);
}
else{
secondNumber.push(number);
}
document.getElementById('answer').innerHTML = number;
}
function change(operator){
current = 'secondNumber';
operation = operator;
if (operation == 'addition'){
return document.getElementById('answer').innerHTML = '+';
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = "-";
}
else if (operator == 'multiplication'){
return document.getElementById('answer').innerHTML = 'x';
}
else if (operator == 'multiplication'){
}
return document.getElementById("answer").innerHTML = '÷';
}
function solve(){
firstNumber = firstNumber.join('');
secondNumber = secondNumber.join('');
firstNumber = parseInt(firstNumber);
secondNumber = parseInt(secondNumber);
if (operation == 'addition'){
return document.getElementById("answer").innerHTML = firstNumber + secondNumber;
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = firstNumber - secondNumber;
}
else if (operation == 'multiplication'){
return document.getElementById("answer").innerHTML = firstNumber * secondNumber;
}
else if (operation == 'division'){
return document.getElementById('answer').innerHTML = firstNumber / secondNumber;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
h1{
text-align: center;
font-family: monospace;
font-weight: bold;
font-size: 75px;
text-shadow: 3px 3px 15px red;
}
#container{
display: flex;
flex-direction: column;
width: 50%;
height: 500px;
margin-left: 25%;
}
.row{
display: flex;
flex-direction: row;
height: 15%;
margin-top: 1%;
width: 100%;
}
button{
width: 30%;
text-align: center;
margin: 5px;
font-size: 35px;
background-color: rgb(255, 0, 0);
border-color: purple;
}
#answer{
border-style: solid;
border-color: red;
border-width: 3px;
border-radius: 5px;
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
#wide{
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
body{
background-image: linear-gradient(to bottom right, rgb(0, 0, 255), rgb(100, 0, 255));
}
<!doctype html>
<html>
<head>
<title>Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="/static/calculator.css">
<script src="/static/calculator.js"></script>
</head>
<body>
<h1>Calculator</h1>
<br />
<div id="container">
<p id="answer"></p>
<button onclick="solve()" id="wide">=</button>
<div class="row">
<button onclick="set(1)">1</button>
<button onclick="set(2)">2</button>
<button onclick="set(3)">3</button>
</div>
<div class="row">
<button onclick="set(4)">4</button>
<button onclick="set(5)">5</button>
<button onclick="set(6)">6</button>
</div>
<div class="row">
<button onclick="set(7)">7</button>
<button onclick="set(8)">8</button>
<button onclick="set(9)">9</button>
</div>
<div class="row">
<button onclick="set(0)">0</button>
<button onclick="change('addition')">+</button>
<button onclick="change('subtraction')">-</button>
</div>
<div class="row">
<button onclick="change('multiplication')">x</button>
<button onclick="change('division')">/</button>
<button onclick="clear()">c</button>
</div>
</div>
</body>
</html>

It seems that clear() requires to bind an event listener in the DOM, for example:
<button id="clear">c</button>
<script>document.getElementById("clear").addEventListener("click", clear);</script>
Or, alternatively, use document.clear() (deprecated) or window.clear().
See related question:
Is "clear" a reserved word in Javascript?
https://developer.mozilla.org/en-US/docs/Web/API/Document/clear
To avoid that, simply rename clear() function to clearResult() and it will work.
See modified snippet below.
In addition, instead of location.reload(); you can simply clear content of the answer as a faster alternative:
document.getElementById('answer').innerHTML = '';
var firstNumber = [];
var secondNumber = [];
let current = 'firstNumber';
var operation;
function clearResult(){
location.reload();
}
function set(number){
if (current == 'firstNumber'){
firstNumber.push(number);
}
else{
secondNumber.push(number);
}
document.getElementById('answer').innerHTML = number;
}
function change(operator){
current = 'secondNumber';
operation = operator;
if (operation == 'addition'){
return document.getElementById('answer').innerHTML = '+';
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = "-";
}
else if (operator == 'multiplication'){
return document.getElementById('answer').innerHTML = 'x';
}
else if (operator == 'multiplication'){
}
return document.getElementById("answer").innerHTML = '÷';
}
function solve(){
firstNumber = firstNumber.join('');
secondNumber = secondNumber.join('');
firstNumber = parseInt(firstNumber);
secondNumber = parseInt(secondNumber);
if (operation == 'addition'){
return document.getElementById("answer").innerHTML = firstNumber + secondNumber;
}
else if (operation == 'subtraction'){
return document.getElementById('answer').innerHTML = firstNumber - secondNumber;
}
else if (operation == 'multiplication'){
return document.getElementById("answer").innerHTML = firstNumber * secondNumber;
}
else if (operation == 'division'){
return document.getElementById('answer').innerHTML = firstNumber / secondNumber;
}
}
<!-- begin snippet: js hide: false console: true babel: false -->
h1{
text-align: center;
font-family: monospace;
font-weight: bold;
font-size: 75px;
text-shadow: 3px 3px 15px red;
}
#container{
display: flex;
flex-direction: column;
width: 50%;
height: 500px;
margin-left: 25%;
}
.row{
display: flex;
flex-direction: row;
height: 15%;
margin-top: 1%;
width: 100%;
}
button{
width: 30%;
text-align: center;
margin: 5px;
font-size: 35px;
background-color: rgb(255, 0, 0);
border-color: purple;
}
#answer{
border-style: solid;
border-color: red;
border-width: 3px;
border-radius: 5px;
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
#wide{
width: 95%;
height: 35px;
text-align: center;
font-size: 25px;
font-weight: bold;
}
body{
background-image: linear-gradient(to bottom right, rgb(0, 0, 255), rgb(100, 0, 255));
}
<!doctype html>
<html>
<head>
<title>Calculator</title>
<meta charset="utf-8">
<link rel="stylesheet" href="/static/calculator.css">
<script src="/static/calculator.js"></script>
</head>
<body>
<h1>Calculator</h1>
<br />
<div id="container">
<p id="answer"></p>
<button onclick="solve()" id="wide">=</button>
<div class="row">
<button onclick="set(1)">1</button>
<button onclick="set(2)">2</button>
<button onclick="set(3)">3</button>
</div>
<div class="row">
<button onclick="set(4)">4</button>
<button onclick="set(5)">5</button>
<button onclick="set(6)">6</button>
</div>
<div class="row">
<button onclick="set(7)">7</button>
<button onclick="set(8)">8</button>
<button onclick="set(9)">9</button>
</div>
<div class="row">
<button onclick="set(0)">0</button>
<button onclick="change('addition')">+</button>
<button onclick="change('subtraction')">-</button>
</div>
<div class="row">
<button onclick="change('multiplication')">x</button>
<button onclick="change('division')">/</button>
<button onclick="clearResult()">c</button>
</div>
</div>
</body>
</html>

Related

Javascript Calculator is returning undefined

I have not been able to figure out why my calculator is returning undefined. I have it set up to return the result but I can't figure out why it doesn't return the actual calculation. I have console.log() my numbers and operator and they will show up but it never calculates. On the screen it returns undefined. Thanks so much to anyone that helps!
JS Code
const screen =document.querySelector('.screen')
const clear =document.querySelector('.clear')
const numberButtons =document.querySelectorAll('.numbers')
const operators =document.querySelectorAll('.operators')
const equal =document.querySelector('.equal')
let previousValue ='';
let currentValue ='';
let result = '';
//code for numbers to show values on screen
numberButtons.forEach(function(numberButton){
numberButton.addEventListener("click",function(){
screen.textContent+=numberButton.value;
currentValue=parseInt(screen.innerText);
})
})
// code for +-/*
operators.forEach(function(operators){
operators.addEventListener("click",function(){
screen.textContent+=operators.value;
currentValue=(screen.innerText);
})
})
//function for math equations
function calculate(operators,previousValue,currentValue) {
console.log(previousValue);
console.log(operators);
console.log(currentValue);
previousValue = parseInt(previousValue)
currentValue = parseInt(currentValue)
if (operators == '+') {
result = previousValue += currentValue
} else if (operators == '-') {
result = previousValue -= currentValue
} else if (operators == '*') {
result = previousValue *= currentValue
} else {
result = previousValue /= currentValue
}
screen.textContent += calculate.value
currentValue = (screen.innerText)
return result ;
}
//function to compute once equal is clicked
equal.addEventListener("click", button => {
screen.textContent+=equal.value;
currentValue=(screen.innerText);
if (previousValue != "" && currentValue != "" && operators != ""){
return result;
}
calculate(operators,previousValue,currentValue)
})
clear.addEventListener('click',() => location.reload());
CSS
html, body {
height: 100%;
width: 100%;
}
div.calc{
font-family: 'Courier New', monospace;
color: #FB6F92;
font-size: 40px ;
font-weight: bolder;
margin-left: 625px;
margin-top: 25px;
}
div.container{
background:#e7e7e7;
width: 500px;
height: 555px;
border-radius: 10px;
border: 5px solid #FB6F92;
margin-left: 500px;
margin-top: 25px;
box-shadow: 10px 10px 10px;
}
div.screen{
border: 5px solid #FB6F92;
color: black;
background: #f8f8ff;
width: 445px;
height: 100px;
border-radius: 10px;
margin-left: 20px;
font-size: 30px;
text-align: right;
font-weight: bold;
font-family: 'Courier New', monospace;
}
button.clear{
width: 450px;
height: 50px;
background:#FFCCF9;
color:black;
border-radius: 5px;
margin-left: 22px;
margin-top: 6px;
}
button.clear:hover{
background:#Ff9cee;
}
button.numbers{
width: 75px;
height: 75px;
background: pink;
color:white;
border-radius: 5px;
margin-left: 35px;
margin-top: 15px;
font-weight: bold;
font-size: 20px;
}
button.numbers:hover{
background: #FB6F92;
}
button.operators{
width: 75px;
height: 75px;
background: #A4E7DF;
color:black;
border-radius: 5px;
margin-left: 35px;
margin-top: 15px;
font-weight: bold;
font-size: 20px;
}
button.operators:hover{
background: #3bc6b6;
#64d4c7
}
button.equal{
width: 190px;
height: 75px;
background: #D1B2EA;
color:black;
border-radius: 5px;
margin-left: 35px;
margin-top: 15px;
font-weight: bold;
font-size: 20px;
}
button.equal:hover{
background:#b07cda;
}
footer{
font-family: 'Courier New', monospace;
color: #FB6F92;
font-size: 36px ;
font-weight: bolder;
margin-left: 510px;
margin-top: 20px;
}
html, body {
height: 100%;
width: 100%;
}
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Calculator TOP Project</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body style = 'background-color :#a0ddfb;'>
<div class = "calc"> Calculator</div>
<div class = "container">
<br>
<div class="screen" value = "screen"></div>
<button class = "clear" onclick="clear();" >Clear</button>
<br>
<button class = 'numbers' value="7" > 7</button>
<button class = 'numbers' value="8">8</button>
<button class = 'numbers' value="9">9</button>
<button class = 'operators' value="÷"> ÷</button>
<br>
<button class = 'numbers' value="4">4</button>
<button class = 'numbers'value="5">5</button>
<button class = 'numbers' value="6">6</button>
<button class = 'operators' value="*" > ×</button>
<br>
<button class = 'numbers' value="1" >1</button>
<button class = 'numbers' value="2" >2</button>
<button class = 'numbers' value="3" >3</button>
<button class = 'operators' value = "-" >-</button>
<br>
<!-- <button class = 'numbers' value=".">.</button> -->
<button class = 'numbers' value ="0" >0</button>
<button class = 'equal' value="=" >=</button>
<button class = 'operators' value = "+" >+</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Looks like you have a bad line.
Observe your js file on this line:
screen.textContent += calculate.value
calculate is the name of your function. It has no attribute value.
You probably want to replace calculate.value to result like so:
screen.textContent += result
Also you have some errors above that:
previousValue = parseInt(previousValue)
currentValue = parseInt(currentValue)
parseInt of an empty String will give you a a value of NaN (Not a number).
You also have a handful of logic bugs that you have to fix.
The undefined bug is just 1 bug that you have to fix.

Couldn't align images to center

I am working on a project where couldn't align images to center. Rock-paper-scissor image align issue where I couldn't align the images to center from where I take responses to display.
let userScore = 0;
let computerScore =0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreboard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const rock_div = document.getElementById("r")
const paper_div = document.getElementById("p")
const scissor_div = document.getElementById("s")
function getComputerChoice(){
const choices =['r','p','s'];
const randomNumber = Math.floor(Math.random()*3);
return choices[randomNumber];
}
function convertToWord(letter){
if(letter =="r") return "rock"
if(letter == "p") return "paper"
return "scissor"
}
getComputerChoice();
function win(userChoice,computerChoice){
userScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you win`
console.log("win " + userScore + ":" +computerScore);
}
function lose(userChoice,computerChoice){
computerScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you loose`
console.log("lose " + userScore + ":" +computerScore);
}
function draw(){
console.log("draw");
}
function game(userChoice){
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice){
case "rs":
case "sp":
case "pr":
win();
break
case "sr":
case "ps":
case "rp":
lose();
break
case "rr":
case "pp":
case "ss":
draw();
break
}
}
function main(){
rock_div.addEventListener('click',function(){
game("r");
})
paper_div.addEventListener('click',function(){
game("p");
})
scissor_div.addEventListener('click',function(){
game("s");
})
}
main();
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: darkcyan;
}
header
{
background-color: whitesmoke;
padding: 20px;
}
header > h1 {
color:darkcyan;
text-align: center;
font-family: Asap, sans-serif;
}
.score-board{
margin: 20px auto;
border: 3px solid white;
border-radius: 10px;
text-align: center;
width:200px;
color: azure;
font-size: 46px;
position: relative;
}
.badge {
background: #50012e;
color: white;
font-size: 20px;
padding: 2px 10px;
font-family: Asap, sans-serif;
}
#user-label{
position: absolute;
top:15px;
left: -25px;
}
#computer-label{
position: absolute;
top:15px;
right: -25px;
}
.result{
font-size: 70px;
color: whitesmoke;
display: flex;
justify-content: center;
}
.result > p {
text-align: center ;
font-weight: bold;
font-family: Asap, sans-serif;
font-size: 20px;
}
.choices {
margin: auto;
text-align: center;
display: inline-block;
justify-content: center;
}
.choices{
border: 4px solid cyan;
border-radius: 50%;
margin:0 20px;
padding: 10px;
transition: all 0.2s ease;;
}
.choices:hover{
cursor: pointer;
background: #242424 ;
}
#action {
text-align: center;
color: azure;
font-weight: bold;
font-size: 20px;
margin-top: 20px;
font-family: Arial, Helvetica, sans-serif;
}
<html>
<head>
<meta charset="utf-8">
<title>
"Rock Paper Scissors"
</title>
<link rel="stylesheet" href="styles.css"></link>
</head>
<body>
<header>
<h1> Rock , Paper , Scissors </h1>
</header>
<div class="score-board">
<div id = "user-label" class = "badge">user</div>
<div id = "computer-label" class = "badge">comp</div>
<span id ="user-score">0</span>:<span id ="computer-score">0</span>
</div>
<div class="result">
<p>Scissor cuts paper,you win.!</p>
</div>
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
<p id="action">Make Your Move</p>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
Image:
i think this solves your problem
let userScore = 0;
let computerScore =0;
const userScore_span = document.getElementById("user-score");
const computerScore_span = document.getElementById("computer-score");
const scoreboard_div = document.querySelector(".score-board");
const result_div = document.querySelector(".result");
const rock_div = document.getElementById("r")
const paper_div = document.getElementById("p")
const scissor_div = document.getElementById("s")
function getComputerChoice(){
const choices =['r','p','s'];
const randomNumber = Math.floor(Math.random()*3);
return choices[randomNumber];
}
function convertToWord(letter){
if(letter =="r") return "rock"
if(letter == "p") return "paper"
return "scissor"
}
getComputerChoice();
function win(userChoice,computerChoice){
userScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you win`
console.log("win " + userScore + ":" +computerScore);
}
function lose(userChoice,computerChoice){
computerScore++;
userScore_span.innerHTML = userScore;
computerScore_span.innerHTML = computerScore;
result_div.innerHTML = `${convertToWord(userChoice)} beats ${convertToWord(computerChoice)},you loose`
console.log("lose " + userScore + ":" +computerScore);
}
function draw(){
console.log("draw");
}
function game(userChoice){
const computerChoice = getComputerChoice();
switch (userChoice + computerChoice){
case "rs":
case "sp":
case "pr":
win();
break
case "sr":
case "ps":
case "rp":
lose();
break
case "rr":
case "pp":
case "ss":
draw();
break
}
}
function main(){
rock_div.addEventListener('click',function(){
game("r");
})
paper_div.addEventListener('click',function(){
game("p");
})
scissor_div.addEventListener('click',function(){
game("s");
})
}
main();
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
background-color: darkcyan;
}
header
{
background-color: whitesmoke;
padding: 20px;
}
header > h1 {
color:darkcyan;
text-align: center;
font-family: Asap, sans-serif;
}
.score-board{
margin: 20px auto;
border: 3px solid white;
border-radius: 10px;
text-align: center;
width:200px;
color: azure;
font-size: 46px;
position: relative;
}
.badge {
background: #50012e;
color: white;
font-size: 20px;
padding: 2px 10px;
font-family: Asap, sans-serif;
}
#user-label{
position: absolute;
top:15px;
left: -25px;
}
#computer-label{
position: absolute;
top:15px;
right: -25px;
}
.result{
font-size: 70px;
color: whitesmoke;
display: flex;
justify-content: center;
}
.result > p {
text-align: center ;
font-weight: bold;
font-family: Asap, sans-serif;
font-size: 20px;
}
.choices {
margin: auto;
text-align: center;
display: inline-block;
justify-content: center;
}
.choices{
border: 4px solid cyan;
border-radius: 50%;
margin:0 20px;
padding: 10px;
transition: all 0.2s ease;;
}
.choices:hover{
cursor: pointer;
background: #242424 ;
}
#action {
text-align: center;
color: azure;
font-weight: bold;
font-size: 20px;
margin-top: 20px;
font-family: Arial, Helvetica, sans-serif;
}
.choices-parent {
display: flex;
justify-content: center;
}
<html>
<head>
<meta charset="utf-8">
<title>
"Rock Paper Scissors"
</title>
<link rel="stylesheet" href="styles.css"></link>
</head>
<body>
<header>
<h1> Rock , Paper , Scissors </h1>
</header>
<div class="score-board">
<div id = "user-label" class = "badge">user</div>
<div id = "computer-label" class = "badge">comp</div>
<span id ="user-score">0</span>:<span id ="computer-score">0</span>
</div>
<div class="result">
<p>Scissor cuts paper,you win.!</p>
</div>
<div class="choices-parent">
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
</div>
<p id="action">Make Your Move</p>
<script src="app.js" charset="utf-8"></script>
</body>
</html>
Add all their images into one div and then apply css {text-align: center} to the newly added div.
<div class="new_div">
<div class="choices" id ="r">
<img src="assets/rock.PNG" alt="rock">
</div>
<div class="choices" id ="p">
<img src="assets/paper.PNG" alt="paper">
</div>
<div class="choices" id ="s">
<img src="assets/Scissor.PNG" alt="scissor">
</div>
</div>
And apply CSS
.new_div{
text-align: center;
}
use flex display for "chooise" scss class and use align-content "center"
you set flex display for pare

Javascript file partially running

So I taught myself coding a few years ago, and got it just enough to put together a few tools for work. I recently had to migrate my site out of CodePen and onto an actual web server. Now I'm having an issue where part of my javascript is executing properly (a portion that empties all other input fields when a user enters an input field using JQuery), but the button that calculates an answer will not work. I believe the .click is not picking it up. Either way I'm not getting error messages, the button just does nothing when I press it.
When I put the code in a snippet to share with you guys, it works (just like it did in CodePen), but the exact same code on my web host does not work. I'm really at a loss here and any help would be greatly appreciated. I feel like I'm missing some small line of code that's supposed to be included in all web files.
$(document).ready(function() {
//Clear out input fields when not selected
$("#sg").focusin(function() {
$("#density").val("");
});
$("#density").focusin(function() {
$("#sg").val("");
});
$("#pounds").focusin(function() {
$("#grams").val("");
$("#percentage").val("");
});
$("#grams").focusin(function() {
$("#percentage").val("");
$("#pounds").val("");
});
$("#percentage").focusin(function() {
$("#pounds").val("");
$("#grams").val("");
});
$(".input_field").focusin(function() {
$("#density").removeClass('highlight');
$("#sg").removeClass('highlight');
$("#pounds").removeClass('highlight');
$("#grams").removeClass('highlight');
$("#percentage").removeClass('highlight');
});
//Calculate on press of enter
$("#button").keypress(function(e) {
if (e.which == 13) {
alert("this is working");
}
});
$("#button").click(function() {
calculateButton();
});
//Calculate values on button hit
function calculateButton() {
function numberWithCommas(x) {
x = x.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(x))
x = x.replace(pattern, "$1,$2");
return x;
}
function removeCommas(x) {
x = x.replace(",", "");
return x;
}
var results = 0;
//Pulling information from input cells
var densityStr = document.getElementById("density").value;
var sgStr = document.getElementById("sg").value;
var poundsStr = document.getElementById("pounds").value;
var gramsStr = document.getElementById("grams").value;
var percentageStr = document.getElementById("percentage").value;
//remove commas from string and then convert string to number
var densityNum = Number(removeCommas(densityStr));
var sgNum = Number(removeCommas(sgStr));
var poundsNum = Number(removeCommas(poundsStr));
var gramsNum = Number(removeCommas(gramsStr));
var percentageNum = Number(removeCommas(percentageStr));
if (densityStr.length !== 0) {
var sgConversion = densityNum / 8.3454;
$("#sg").val(sgConversion.toFixed(3));
$("#density").addClass('highlight');
} else if (sgStr.length !== 0) {
var densityConversion = sgNum * 8.3454;
$("#density").val(densityConversion.toFixed(3));
$("#sg").addClass('highlight');
}
if (poundsStr.length !== 0) {
$("#pounds").addClass("highlight");
densityNum = document.getElementById("density").value;
var gramsConversion = poundsNum * 119.83;
var percentageConversion = poundsNum / densityNum * 100;
$("#grams").val(gramsConversion.toFixed(0));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (gramsStr.length !== 0) {
$("#grams").addClass("highlight");
densityNum = document.getElementById("density").value;
var poundsConversion = gramsNum / 119.83;
var percentageConversion = poundsConversion / densityNum * 100;
$("#pounds").val(poundsConversion.toFixed(2));
$("#percentage").val(percentageConversion.toFixed(2));
} else if (percentageStr.length !== 0) {
$("#percentage").addClass("highlight");
densityNum = document.getElementById("density").value;
var percentageDec = percentageNum / 100;
var poundsConversion = densityNum * percentageDec;
var gramsConversion = poundsConversion * 119.83;
$("#pounds").val(poundsConversion.toFixed(2));
$("#grams").val(gramsConversion.toFixed(2));
}
}
});
body {
margin: 0;
font-family: 'Lato', sans-serif;
background: #d2d2d2;
}
p {
text-align: center;
}
conatiner {
max-width: 1024px;
margin: 0 auto;
}
#navbarContainer {
background: #F44336;
overflow: hidden;
width: 100%;
margin: 0;
}
.navbar {
float: left;
display: block;
font-family: 'Lato', sans-serif;
height: 40px;
width: 200px;
line-height: 40px;
text-align: center;
background: #F44336;
text-decoration: none;
color: #212121;
}
.navbar:hover {
background: #E57373;
color: white;
}
.active {
background: #C62828;
color: white;
}
#formContainer {
width: 450px;
background: #FDFFFC;
margin: 50px auto;
padding: 0px;
border-radius: 8px;
overflow: hidden;
}
#formContainer header {
width: 100%;
height: 130px;
background-color: #3cba54;
overflow: auto;
color: white;
}
header h1 {
margin: 35px 0 0 0;
text-align: center;
line-height: 30px;
}
header h3 {
line-height: 40px;
text-align: center;
margin: 0;
}
#heading {
background-color: #3cba54;
height: 40px;
color: white;
margin-bottom: 25px;
margin-left: -30px;
}
#heading h3 {
line-height: 40px;
}
form {
padding: 20px 0 0 20px;
text-align: center;
}
label {
display: inline-block;
width: 220px;
text-align: right;
}
#myForm .input_field {
margin-left: 20px;
margin-bottom: 10px;
font-size: 20px;
padding-left: 10px;
width: 125px;
height: 35px;
font-size: 17px;
border-radius: 3px;
background-color: #E0E0E0;
border: none;
}
#button {
display: block;
border-radius: 6px;
width: 200px;
height: 50px;
padding: 8px 15px 8px 15px;
margin: 0 auto;
margin-bottom: 50px;
font-size: 16px;
box-shadow: 0 6px #540000;
background-color: #FF3636;
border: none;
outline: none;
}
#button:active {
background-color: #B81B1B;
box-shadow: 0 1px #27496d;
transform: translateY(5px);
}
.highlight {
background: #FFEB3B !important;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
</body>
</html>
Sometimes putting script tags before the elements on the page can cause issues. You can try to put the scripts at the bottom of the body like this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="container">
<div id="navbarContainer">
<a class="navbar" id="62" href="https://s.codepen.io/awheat/debug/MpMrEo/yYAyLDjQWgKr">326 IAC 6-2 Tool</a>
<a class="navbar" id="63" href="https://s.codepen.io/awheat/debug/gWmazm/NQkzYnjeQZyA">326 IAC 6-3 Tool</a>
<a class="navbar active" id="voc" href="https://s.codepen.io/awheat/debug/qVpPNm/VGAWNnJYBjZr">VOC Conversion Tool</a>
</div>
<div id="formContainer">
<header>
<h1>VOC Conversion Tool</h1>
<h3>(for conversion of VOC data to other units)</h3>
</header>
<form id="myForm">
<label>Density of Coating (lbs/gal): </label><input type="text" id="density" class="input_field">
<label>Specific Graviy: </label><input type="text" id="sg" class="input_field">
<div id="heading">
<h3>VOC Content</h3>
</div>
<label>Pounds per Gallon (lbs/gal): </label><input type="text" id="pounds" class="input_field">
<label>Grams per Liter (g/L): </label><input type="text" id="grams" class="input_field">
<label>Percentage (%): </label><input type="text" id="percentage" class="input_field"><br><br>
<input type="button" id="button" value="Calculate" autofocus>
</form>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

JS addition game: how do I display 4 possible answers, 3 of them are random and 1 is the correct answer ? (Codepen included)

I am building a game out of JS. the rules of the game are simple: you are asked what (num1) + (num2) equals (as you can see in the codepen).
In the game you have 4 possible choices to answer the question.
We're I'm stuck right now is creating those possible options: I would like to display three random numbers that are false and one number that is the correct sum.
my JS:
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var options = {
option1: document.getElementById('option1'),
option2: document.getElementById('option2'),
option3: document.getElementById('option3'),
option4: document.getElementById('option4'),
}
Here is my codepen:
https://codepen.io/teenicarus/pen/Oxaaoe
How do i do this?
I appreciate all answers
The solution is a little complex, it will be so long to describe every row, so feel free to ask if anything isn't clear. Need to say, that the order of numbers on cards is randomly generated too. Here it is:
function shuffle(o) {
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function startGame() {
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
var otherNumbers = [];
var counter = 0;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var options = {
option1: document.getElementById('option1'),
option2: document.getElementById('option2'),
option3: document.getElementById('option3'),
option4: document.getElementById('option4'),
}
function generateRandomNumber() {
for (var i = 0; counter < 3; i++) {
var num = Math.floor((Math.random() * 30) + 10);
if (num !== result && counter < 3) {
counter++;
otherNumbers.push(num);
} else {
generateRandomNumber();
}
}
}
generateRandomNumber();
otherNumbers.push(result);
otherNumbers = shuffle(otherNumbers);
var arrCount = otherNumbers.length - 1;
for (var key in options) {
if (arrCount >= 0) {
options[key].innerHTML = otherNumbers[arrCount];
arrCount--;
}
}
}
startGame();
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 60px;
}
.App-header {
background-color: #222;
height: 180px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
#keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.text-info {
color: #fff;
font-weight: bold;
font-size: 2.1rem;
}
.question {
font-size: 2rem;
}
.options {
margin: 5%;
display: flex;
margin-right: -12px;
margin-left: -12px;
flex-direction: row;
flex-wrap: wrap;
align-items: stretch;
flex: 1 0 auto;
}
.fields {
display: flex;
padding: 12px;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
flex: 1;
}
.field-block {
display: flex;
min-height: 160px;
padding: 10%;
flex-direction: row;
justify-content: center;
align-items: center;
/*flex: 1 0 auto;*/
border-radius: 4px;
background-color: #f9bad0;
font-size: 6rem;
color: #fff;
cursor: pointer;
}
.quiz {
color: #ddd;
margin: 2%;
background-color: #ec1561;
padding: 2%;
width: 90%;
position: relative;
}
.button {
display: flex;
height: 48px;
padding-right: 16px;
padding-left: 16px;
flex-direction: row;
justify-content: center;
align-items: center;
flex: 0 0 auto;
border-radius: 4px;
background-color: #2fcaaa;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
transition: box-shadow 200ms ease-out;
color: #fff;
font-weight: 500;
text-align: center;
cursor: pointer;
}
.quiz .after {
position: absolute;
top: 5%;
left: 5%;
width: 90%;
height: 80%;
/*display: none;*/
color: #FFF;
text-align: center;
align-items: center;
justify-content: center;
display: flex;
opacity: 0.8;
font-size: 3rem;
}
.correct {
background-color: green;
}
.wrong {
background-color: #D91E18;
}
.hide {
display: none !important;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Adding 2 Numbers | Happy Learning!</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>
<body>
<img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/>
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block" id="option1">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option2">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option3">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option4">
10
</div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button" onclick="startGame()">Play Again</a>
</div>
</div>
</div>
<script src='index.js'></script>
</body>
</html>
Here is a solution you can refer.
document.addEventListener("DOMContentLoaded", function(event) {
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
var opts = [];
for(var i=0;i<3;i++){
opts.push(findRandom(result,opts));
}
opts.push(result);
opts.sort();
for(var i=1;i<5;i++){
document.getElementById('option'+i).innerHTML = opts[i-1];
}
});
function findRandom(n,opts){
var result = 0;
while(result !=n && result == 0){
result = Math.floor(Math.random() * (n + 1));
if(opts.indexOf(result) >0){
result = 0;
}
}
return result;
}
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 60px;
}
.App-header {
background-color: #222;
height: 180px;
padding: 20px;
color: white;
}
.App-intro {
font-size: large;
}
#keyframes App-logo-spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.text-info {
color: #fff;
font-weight: bold;
font-size: 2.1rem;
}
.question {
font-size: 2rem;
}
.options {
margin: 5%;
display: flex;
margin-right: -12px;
margin-left: -12px;
flex-direction: row;
flex-wrap: wrap;
align-items: stretch;
flex: 1 0 auto;
}
.fields {
display: flex;
padding: 12px;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
flex: 1;
}
.field-block {
display: flex;
min-height: 160px;
padding: 10%;
flex-direction: row;
justify-content: center;
align-items: center;
/*flex: 1 0 auto;*/
border-radius: 4px;
background-color: #f9bad0;
font-size: 6rem;
color: #fff;
cursor: pointer;
}
.quiz {
color: #ddd;
margin: 2%;
background-color: #ec1561;
padding: 2%;
width: 90%;
position: relative;
}
.button {
display: flex;
height: 48px;
padding-right: 16px;
padding-left: 16px;
flex-direction: row;
justify-content: center;
align-items: center;
flex: 0 0 auto;
border-radius: 4px;
background-color: #2fcaaa;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, .05), 0 2px 12px 0 rgba(0, 0, 0, .1);
transition: box-shadow 200ms ease-out;
color: #fff;
font-weight: 500;
text-align: center;
cursor: pointer;
}
.quiz .after {
position: absolute;
top: 5%;
left: 5%;
width: 90%;
height: 80%;
/*display: none;*/
color: #FFF;
text-align: center;
align-items: center;
justify-content: center;
display: flex;
opacity: 0.8;
font-size: 3rem;
}
.correct {
background-color: green;
}
.wrong {
background-color: #D91E18;
}
.hide {
display: none !important;
}
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Adding 2 Numbers | Happy Learning!</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css">
</head>
<body>
<img alt="Join Slack" height="40" width="139" src="http://i.imgur.com/0Lne5Vr.png"/>
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block" id="option1">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option2">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option3">
10
</div>
</div>
<div class="fields animated zoomIn">
<div class="field-block" id="option4">
10
</div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button">Play Again</a>
</div>
</div>
</div>
<script src='index.js'></script>
</body>
</html>
As per my comment, you will need to re-run that number generator to generate new and incorrect answers for the 3 remaining options. There are a few things that you want to watch out for:
You have to avoid collisions, i.e. do not generate numbers that are the same as the answer, or the same as any pre-generated incorrect options. We can make this simple check by using a while loop
You can use a generic function to generate num1 + num2, so that it can be re-used again to generate incorrect answers.
Instead of giving your options unique IDs, simply give them a generic class, e.g. <div class="field-block option"></div> . We want to be able to know how many options we have so that we generate correct number of answer + incorrect answers.
You might want to shuffle your answers array before appending them to the DOM, otherwise they will all have the first element containing the correct answer.
Side note: Although it is not mentioned in your original answer, I expected that you want to know which is the correct answer when a user click on that option. When a click event is fired from the option, you can simply get the index of the option, and check it against the answers array. If the option's index matches the index of the correct answer in the array, then you are good to go.
In the code snippet below, I have stripped the stylesheet and some unnecessary markup:
// FY shuffle
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
}
// Function that generates all options
var generateAllOptions = function() {
// Number generator
var getRandomNumber = function() {
return Math.floor((Math.random() * 30) + 10);
};
// Get the question + correct answer
var num1 = getRandomNumber();
var num2 = getRandomNumber();
var correctAnswer = num1 + num2;
var answers = [correctAnswer];
// Update question
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;
// Generate incorrect answers/options, but make sure there are no collisions
var options = document.querySelectorAll('.options .option');
while(answers.length < options.length) {
var incorrectAnswer = getRandomNumber() + getRandomNumber();
if (answers.indexOf(incorrectAnswer) === -1)
answers.push(incorrectAnswer);
}
// Shuffle answers
shuffle(answers);
// Store index of correct answer
var correctIndex = answers.indexOf(correctAnswer);
// Append shuffled answers to options
for (var i = 0; i < options.length; i++) {
var option = options[i];
// Write answer values into innerHTML
option.innerHTML = answers[i];
// Bind click event to all options, use IIFE!
(function(idx) {
option.addEventListener('click', function() {
if (idx === correctIndex) {
alert('You have selected the right answer!');
} else {
alert('That is an incorrect answer.');
}
});
})(i);
}
};
generateAllOptions();
.option {
font-weight: bold;
background-color: steelblue;
color: #fff;
border-radius: 4px;
padding: 10px;
margin: 5px;
}
<div>
<h1>Adding Game</h1>
<p id="demo">In this lecture, we will cover the game to add 2 numbers.</p>
</div>
<hr>
<div class="quiz">
<div class="quiz-content">
<div class="question">
What is the sum of <span class="text-info" id="field1">5</span> and <span class="text-info" id="field2">5</span>?
</div>
<div class="options">
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
<div class="fields animated zoomIn">
<div class="field-block option"></div>
</div>
</div>
<div class="after hide" id="after">
</div>
<div class="play-again">
<a class="button">Play Again</a>
</div>
</div>
</div>
Try this simple solution. This generates 4 unique random options out of which one option is the correct one. The option number of the correct answer is also random.
You only need to modify your js.
var num1 = Math.floor((Math.random() * 30) + 10);
var num2 = Math.floor((Math.random() * 30) + 10);
var result = num1 + num2;
var ansIndex=(Math.floor((Math.random()*10))%4)+1; //this index will be the position of the correct answer
var option=[];
//the below loop fills the options array with random but unique options
for(var i=0;i<4;i++){
var temp=Math.floor((Math.random() * 30) + 10);
if(final.indexOf(temp)==(-1)){
option.push(temp);
continue;
}
else{
i--;
}
}
//finally the correct option is overwritten
option[ansIndex-1]=result;
var answer=document.getElementsByClassName("field-block");
answer[0].innerHTML=option[0];
answer[1].innerHTML=option[1];
answer[2].innerHTML=option[2];
answer[3].innerHTML=option[3];
document.getElementById('field1').innerHTML = num1;
document.getElementById('field2').innerHTML = num2;

JS - How to return a calculation and clear the display?

So when I run this code and look at the console I get the response:
"The specified value "undefined" is not a valid number. The value must match to main.js:45 the following regular expression: -?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
I've updated the HTML to do the onclick for the total in the JS. I've also put in an onclick to clear the display in the HTML. I think I need to actually put in a function to cleardisplay in JS as well.
What I'm struggling with is what's the best way to update JS to accept the values and return a response of the calculation?
At the moment I'm trying to do eval but I guess I'm using it wrong or not connecting it properly.
Let me know if I'm completely wrong with what I need to update this as well.
For a better look:
jsfiddle
let number = document.getElementsByClassName("number");
let operate = document.getElementsByClassName("operate");
let clear = document.getElementById("clear");
let sub=document.getElementById("sub");
let multiply = document.getElementById("mul");
let divide = document.getElementById("divide");
let add = document.getElementById("plus");
let display = document.querySelector("input");
//Functions or For Loops
for (let i = 0; i < number.length; i++) {
number[i].addEventListener("click", function() {
let inputValue = entry.querySelector("input").value;
let buttonValue = this.textContent;
if (buttonValue === "C") {
display.value = " ";
} else {
entry.innerHTML += buttonValue;
}
})
}
for (let i = 0; i < operate.length; i++) {
operate[i].addEventListener("click", function() {
let inputValue = entry.querySelector("input").value;
let buttonValue = this.textContent;
if (buttonValue === "C") {
entry.innerHTML = " ";
} else {
entry.innerHTML += buttonValue;
}
})
}
function total(){
let display = document.querySelector("input");//equal in HTML using "total()" for the onclick
x=display.value;
x=eval(x);
display.value=x;
}
/*Background color: #64B255;
Border color between buttons: #83C178;
Color for numbers, equal enterfield: white;
Operators (not =) color: #4B6E44;
Hover color for equal and clear: #83C178*/
.wrapper{
max-width: 375px;
margin: 0 auto;
margin-top: 50px;
}
section {
background-color: #64B255;
display: flex;
display: flex;
color: white;
text-align: center;
justify-content: center;
flex-wrap: wrap;
}
.number{
border: 1px solid gray;
box-sizing: border-box;
width:80px;
flex-grow: 1;
height: 80px;
}
#entry{
flex-grow: 3;
width: 245px;
font-size: 30px;
text-align: right;
}
#entry:hover{
background-color: #83C178;
}
#clear{
border: 2px solid gray;
box-sizing: border-box;
width:80px;
flex-grow: 1;
height: 80px;
}
.dot{
border: 1px solid gray;
box-sizing: border-box;
width:80px;
flex-grow: 1;
height: 80px;
}
.dot:hover{
background-color: #83C178;
}
.operate{
background-color: #83C178;
color: #4B6E44;
box-sizing: border-box;
width: 80px;
border: 1px solid gray;
flex-grow: 1;
height: 80px;
font-weight: 100;
}
.operate:hover{
color:white;
}
.number:hover{
background-color: #83C178;
}
input{
width: 20%;
height: 90%;
background-color: #64B255;
border-color: transparent;
text-align: right;
font-size: 60%;
color: white;
padding-bottom: 5px;
}
<body>
<div class="wrapper">
<section class="container">
<div class="clear" id="clear" onclick="clearDisplay()"><h1>C</h1></div>
<div id="entry"><input id="entryText" type="number"></div>
</section>
<section class="keys">
<div class="number seven" value="7"><h1>7</h1></div>
<div class="number eight" value="8"><h1>8</h1></div>
<div class="number nine" value="9"><h1>9</h1></div>
<div class="operate divide" id="divide"><h1>/</h1></div>
<div class="number four" value="4"><h1>4</h1></div>
<div class="number five" value="5"><h1>5</h1></div>
<div class="number six" value="6"><h1>6</h1></div>
<div class="operate mult" id="mul"><h1>x</h1></div>
<div class="number one" value="1"><h1>1</h1></div>
<div class="number two" value="2"><h1>2</h1></div>
<div class="number three" value="3"><h1>3</h1></div>
<div class="operate minus" id="sub"><h1>-</h1></div>
<div class="number zero" value="0"><h1>0</h1></div>
<div class="dot"><h1>.</h1></div>
<div class="operate equal" id="equal" onclick="total()"><h1>=</h1></div>
<div class="operate plus" id="plus"><h1>+</h1></div>
</section>
</div>
<script src="main.js"></script>
</body>
You have to add the clearDisplay function:
function clearDisplay(){
display.value = "";
}
Also you have to ask if the operator selected is equal (=). You can't add the = symbol to the input. Then your second for must look like this:
for (let i = 0; i < operate.length; i++) {
operate[i].addEventListener("click", function() {
let inputValue = entry.querySelector("input").value;
let buttonValue = this.textContent;
if (buttonValue === "C") {
entry.innerHTML = " ";
} else if(buttonValue !== "="){
entry.innerHTML += buttonValue;
}
})
}

Categories