This is my first time using a JS function and I want the answer to 2*2 to appear on the screen when the equals button is clicked. This is my code that isn’t working:image of calculator I’m working on
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculator</title>
<rel ="stylesheet">
</head>
<body>
<div class="calculator">
<div class="screen"><p id="sum"><span id="n1">2</span> × <span id="n2">2</span></p></div>
<script>
var a = #n1
var b = #n2
function myFunction(a,b) {
return a * b;
}
</script>
<div class="container-buttons">
<div class="buttons">7</div>
<div class="buttons">8</div>
<div class="buttons">9</div>
<div class="buttons division">÷</div>
<div class="buttons">4</div>
<div class="buttons">5</div>
<div class="buttons">6</div>
<div class="buttons multiplication">×</div>
<div class="buttons">1</div>
<div class="buttons">2</div>
<div class="buttons">3</div>
<div class="buttons substraction">−</div>
<div class="buttons">0</div>
<div class="buttons">.</div>
<div class="buttons equals"><input id="sum-answer" type="button" onclick="document.getElementById('sum').innerHTML=myFunction(a,b)" value="=">
</div>
<div class="buttons addition">+</div>
</div>
</div>
</body>
</html>
I created a function to return the result of a * b. Inside an input element of button type, I’ve set onclick property to go to the relevant element – which is the p element (id="sum") inside the div element (id="screen") – and used document.getElementById("sum").innerHTML=myFunction(a,b). But this isn’t working.
3
Answers
If you set your variables
a
andb
to numbers instead, your function works.#n1
and#n2
are not correct javascript syntax.I guess what you are after is to get the number that is in
#n1
and#n2
You can do this by getting the content when you are running the function.
ERROR:
#n1
this is not a right way to use id’s , so i updated code.it may helpful to you.Here is full example
look below