The calculator won't display the right results - javascript

I would like to ask a bit of help. I was creating a simple calculator. The problem is my calculator displays the same results everytime. The addition would display nothing, the subtraction and multiplication would display 0, and the division and modulo would display NaN. Here is my code:
let a = document.getElementById("num1").innerHTML;
let b = document.getElementById("num2").innerHTML;
function addFunction() {
let add = a + b;
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = a - b;
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = a * b;
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = a / b;
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = a % b;
document.getElementById("result").innerHTML = modulo;
}
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1">
<input id="num2">
<br>
<br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>

You should get values of input not innerHTML like this
var a = document.getElementById("num1").value
var b = document.getElementById("num2").value
And then convert it to number like this
a = parseFloat(a)
b = parseFloat(b)

You need to do this:
let a = parseFloat(document.getElementById("num1").value);
let b = parseFloat(document.getElementById("num2").value);

You need .value to get the text of the input field, this will return a string so you also need to use the Unary Plus (+) to convert it to a number:
+document.getElementById("num1").value;
+document.getElementById("num2").value;
Since the content of both input boxes change throughout the program, you would need to run the lines above mulitple times to get the updated content. You can do this with functions:
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
To prevent the user from entering characters that aren't numbers you can also set the input type:
<input id="num1" type="number">
<input id="num2" type="number">
Full code:
<html>
<body>
<div class="container">
<h2>Simple Calculator</h2>
<p>How to operate: Enter two numbers first in the textboxes. Next, press the button of the respective operand. Lastly, a result will come up under the calculator.</p>
<input id="num1" type="number">
<input id="num2" type="number">
</br>
</br>
<button onclick="addFunction()">+</button>
<button onclick="subtractFunction()">-</button>
<button onclick="multiplyFunction()">*</button>
<button onclick="divideFunction()">/</button>
<button onclick="moduloFunction()">%</button>
<p>Result: </p>
<p id="result">
<p>
</div>
<script>
function getA() {
return +document.getElementById("num1").value;
}
function getB() {
return +document.getElementById("num2").value;
}
function addFunction() {
let add = getA() + getB();
document.getElementById("result").innerHTML = add;
}
function subtractFunction() {
let subtract = getA() - getB();
document.getElementById("result").innerHTML = subtract;
}
function multiplyFunction() {
let multiply = getA() * getB();
document.getElementById("result").innerHTML = multiply;
}
function divideFunction() {
let divide = getA() / getB();
document.getElementById("result").innerHTML = divide;
}
function moduloFunction() {
let modulo = getA() % getB();
document.getElementById("result").innerHTML = modulo;
}
</script>
</body>
</html>

Related

How do I make these functions shorter

I was making a simple calculator with two input boxes for each number, and four buttons for each operation underneath. After pressing one of the buttons (Ex:Add) They would perform the operation. However, inside each function I had to keep writing these two lines:
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
Is there a way I could write these before I make each individual function? Could someone with more skill possibly show me what I could do?
function add() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 + Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function sub() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 - Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function mul() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 * Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function div() {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var Total = Value1 / Value2;
document.getElementById('demo').innerHTML = "Total: " + Total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Is there a way I could write these before I make each individual function?
You can get the elements just once:
const input1 = document.getElementById("Value1");
Then when you need its value:
const value1 = input1.valueAsNumber;
In general, you can usually write a function to avoid duplicated logic. Probably not appropriate in this case, but for example:
function getValueAsNumber(id) {
return document.getElementById(id).valueAsNumber;
}
then
const value1 = getValueAsNumber("Value1");
A couple of side notes:
In JavaScript and related languages, the overwhelming convention is to use an initial lower case letter for variables that don't refer to constructor functions. So value1 rather than Value1, value1Element rather than Value1Element, etc.
var is no longer best practice in JavaScript. In new code, prefer let or const because of their more useful scoping.
When putting just plain text in an element, you're better off using textContent rather than innerHTML, because the browser doesn't try to parse the text you give it as HTML.
onxyz-attribute-style event handlers are not best practice, not least because the functions they call have to be globals, and the global namespace is crowded. Consider using modern event handling (addEventListener and the like).
Just for an example, here's your code with some of the above applied, but without going overboard:
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
gid("add").addEventListener("click", () => {
const total = input1.valueAsNumber + input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("sub").addEventListener("click", () => {
const total = input1.valueAsNumber - input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("mul").addEventListener("click", () => {
const total = input1.valueAsNumber * input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
gid("div").addEventListener("click", () => {
const total = input1.valueAsNumber / input2.valueAsNumber;
demo.textContent = "Total: " + total;
});
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
Or we could abstract away everything but the operation itself (just for fun):
const gid = id => document.getElementById(id);
const input1 = gid("Value1");
const input2 = gid("Value2");
const demo = gid("demo");
const clickHandler = (id, operation) => {
// ^^^^^^^^^
gid(id).addEventListener("click", () => {
const total = operation(input1.valueAsNumber, input2.valueAsNumber);
// ^^^^^^^^^
demo.textContent = "Total: " + total;
});
};
clickHandler("add", (a, b) => a + b);
// ^^^^^^^^^^^^^^^
clickHandler("sub", (a, b) => a - b);
clickHandler("mul", (a, b) => a * b);
clickHandler("div", (a, b) => a / b);
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" id="add">Add</button>
<button type="button" id="sub">Subtract</button>
<button type="button" id="mul">Multiply</button>
<button type="button" id="div">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You could even go further than that, but it starts getting hard to follow. :-)
You can make a function to get the value of an element by ID, and re-use it, also you can create 1 function that will show the total as well.
function showTotal(total) {
document.getElementById('demo').innerHTML = "Total: " + total;
}
function getValue(id) {
return document.getElementById(id).valueAsNumber;
}
function add() {
showTotal(getValue("Value1") + getValue("Value2"));
}
function sub() {
showTotal(getValue("Value1") - getValue("Value2"));
}
function mul() {
showTotal(getValue("Value1") * getValue("Value2"));
}
function div() {
showTotal(getValue("Value1") / getValue("Value2"));
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>
Some suggestions:
Let's separate the calculating from the formatted displaying. We'll have one function to calculate (+, -, /, *) and a different function to handle innerHTML-setting.
Since the calculations are all in one function, that removes the redundancy of multiple document.getElementById calls throughout your code.
We can use a switch() statement to determine the operation to apply, although a standard if()/else() also would work.
Working demo...
function operate(e) {
var Total = getOperationTotal(e);
document.getElementById('demo').innerHTML = "Total: " + Total;
}
function getOperationTotal(e) {
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
var total;
switch(e.target.id) {
case 'add-button':
total = Value1 + Value2;
break;
case 'subtract-button':
total = Value1 - Value2;
break;
case 'multiply-button':
total = Value1 * Value2;
break;
case 'divide-button':
total = Value1 / Value2;
break;
}
return total;
}
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button id="add-button" type="button" onclick="operate(event)">Add</button>
<button id="subtract-button" type="button" onclick="operate(event)">Subtract</button>
<button id="multiply-button" type="button" onclick="operate(event)">Multiply</button>
<button id="divide-button" type="button" onclick="operate(event)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
You can define global variables and additionally add onchange functions for the input, so as soon as you change the number the value changes in JS too.
var Value1 = document.getElementById('Value1').valueAsNumber;
var Value2 = document.getElementById('Value2').valueAsNumber;
function updateNr(id){
(id === 1) ? Value1 = document.getElementById('Value1').valueAsNumber : Value2 = document.getElementById('Value2').valueAsNumber;
}
function add() {
var Total = Value1 + Value2;
postAnswer(Total);
}
function sub() {
var Total = Value1 - Value2;
postAnswer(Total);
}
function mul() {
var Total = Value1 * Value2;
postAnswer(Total);
}
function div() {
var Total = Value1 / Value2;
postAnswer(Total);
}
function postAnswer(total){
document.getElementById('demo').innerHTML = "Total: " + total;
}
First Number: <input onchange="updateNr(1)" type="number" id="Value1"><br><br>
Second Number: <input onchange="updateNr(2)" type="number" id="Value2"><br><br>
<button type="button" onclick="add()">Add</button>
<button type="button" onclick="sub()">Subtract</button>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="action(this)">Add</button>
<button type="button" onclick="action(this)">Subtract</button>
<button type="button" onclick="action(this)">Multiply</button>
<button type="button" onclick="action(this)">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
<script>
action = (e) => {
const Value1 = document.getElementById('Value1').valueAsNumber;
const Value2 = document.getElementById('Value2').valueAsNumber;
let Total = null;
switch(e.textContent) {
case 'Add':
Total = Value1 + Value2;
break;
case 'Subtract':
Total = Value1 - Value2;
break;
case 'Multiply':
Total = Value1 * Value2;
break;
case 'Divide':
Total = Value1 / Value2;
break;
}
document.getElementById('demo').innerHTML = `Total: ${Total}`;
}
</script>
</body>
We dont need to write each function for each calculation, Try to reuse the code insted of re-writing it, Since you are trying to execute the same logic but only the arithmetic operators are changed in each function you defined, we can write a single function and change the operators depending on the calculations we intend to perform. Below code uses function calculate(operation) which takes operation as a parameter and gives us the result depending on the argument passed.
Always try to use let insted of var as let has block scope but var doesn't
Also for better code readability and consistency follow naming conventions to name your variables
function calculate(operation){
let total;
let value1 = document.getElementById('Value1').valueAsNumber;
let value2 = document.getElementById('Value2').valueAsNumber;
if(operation == 'add') total = value1 + value2;
else if(operation == 'sub') total = value1 - value2;
else if(operation == 'multiply') total = value1 * value2;
else if(operation == 'devide') total = value1 / value2;
document.getElementById('demo').innerHTML = "Total: " + total;
}
<body style="text-align:center"><br><br>
First Number: <input type="number" id="Value1"><br><br>
Second Number: <input type="number" id="Value2"><br><br>
<button type="button" onclick="calculate('add')">Add</button>
<button type="button" onclick="calculate('sub')">Subtract</button>
<button type="button" onclick="calculate('multiply')">Multiply</button>
<button type="button" onclick="calculate('devide')">Divide</button>
<p id="demo" style="color:red;font-size:20px"></p>
</body>

Difference between a given number and 13 displays -13 for every number I enter

Code:
<!DOCTYPE html>
<html>
<head>
<title>xxxxxxxxxxx</title>
</head>
<input id="nr1" type="text"></br>
<input id="calc" type="button" onClick="calc();return false;" value="calc">
<div id="result"></div>
<script>
const nr1 = document.getElementById("nr1").value;
const nr2 = 13;
const button = document.getElementById("calc");
function calc() {
if(nr1 - nr2 >= 13){
document.getElementById("result").innerHTML = (nr1-nr2)*2;
}
else {
document.getElementById("result").innerHTML = nr1-nr2;
}
}
</script>
</body>
</html>
Why does it display -13 for every number I enter?
I think I'm missing something, but I just can't get what's happening.
The value of user input is stored at DOM load which is empty at that point. In other words, cache the input, not its value. The input must be converted to a number to perform arithmetic.
const
nr2 = 13,
nr1 = document.getElementById("nr1"),
button = document.getElementById("calc");
function calc() {
let n1 = Number( nr1.value ); // convert to number. See browser support
if(n1 - nr2 >= 13) {
document.getElementById("result").innerHTML = (n1-nr2)*2;
} else {
document.getElementById("result").innerHTML = n1-nr2;
}
}
<input id="nr1" type="text"></br>
<input id="calc" type="button" onClick="calc();return false;" value="calc">
<div id="result"></div>

unexpected value in my feet to meters converter with pure javascript

//I'm trying to get a result in meters out of an input in feet.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
//For any number I type I get 0 as answer.
var feetInput = document.getElementById("feet-input").value;
var result = document.getElementById("result");
var total;
function calculate(){
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
For any number I type get 0 as answer.
Because your var feetInput = document.getElementById("feet-input").value; is only executed once you need to fetch always latest value on function call as below
//var feetInput = document.getElementById("feet-input").value;//only executed once
var result = document.getElementById("result");
var total;
function calculate(){
var feetInput = document.getElementById("feet-input").value;
total = feetInput * 0.3048;
result.innerHTML = total;
return total;
}
function clear(){
feetInput.value = "";
result.value = "";
}
//For any number I type get 0 as result.
<div id="inner-wrapper">
<label for="feet-input">Enter feet
</label>
<input type="number" id="feet-input" placeholder="Feet">
<label for="result">Result
</label>
<div id="result"></div>
<button id="calculate" onclick="calculate()">Calculate</button>
<button id="clear" onclick="clear()">Clear</button>
</div>
The only issue that you have is that the value from feet-input is ONLY read when the page is loaded.
You'll need to get the value of feet-input before you do the calculation.
Just add var feetInput = document.getElementById("feet-input").value; to the line immediately after function calculate(){
Codepen: https://codepen.io/DeathCamel57/pen/xPPGrp?editors=0010

How can I make my button compare the users answer with a "correct" answer?

I'm trying to make my first input field automatically display a random multiplication sum, the user should then answer that sum in the second input field. Then when the user would click the button "check my answer", and a pop-up window.alert would appear saying either "You did it" or "Wrong!" etc.
Plus, for some reason, when I delete that empty function, my multiplication sums stop working! Can anyone shed some light?
Here's my code:
var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
var Question = x + " times " + y;
document.getElementById("inputVal").value = Question;
return Question;
}
function genAnswer() {
answer = x * y;
return answer;
}
window.onload = genQuestion;
function buttonPressed() {
var userAnswer = document.getElementById("outputVal").value;
if (answer === userAnswer) {
alert("Correct- Well Done!");
}
else {
alert("Wrong- Please try again!");
}
}
function d() {
}
<h1>Learn to Multiply Website</h1>
<form name="myForm" id="myForm" action="#">
<label>What is</label>
<input id="inputVal" name="inputVal" type="text"/>
<br>
<label>The answer is</label>
<input name="outputVal" id="outputVal" type="text"/>
<br>
<button class="button" onclick="buttonPressed()">Check my Answer</button>
</form>
You are using answer which in not declared.
You can directly call you answer function to genAnswer to compare with question
changed === to == for automatic type conversion.
Updated code
var x = Math.floor(Math.random() * 12) + 1;
var y = Math.floor(Math.random() * 12) + 1;
function genQuestion() {
var Question = x + " times " + y;
document.getElementById("inputVal").value = Question;
return Question;
}
function genAnswer() {
answer= x * y;
return answer;
}
window.onload = genQuestion;
function buttonPressed(){
var userAnswer = document.getElementById("outputVal").value;
if (userAnswer == genAnswer()){
alert("Correct- Well Done!");
}
else {alert("Wrong- Please try again!");}
}
function d(){}
<h1>Learn to Multiply Website</h1>
<form name="myForm" id="myForm" action="#">
<label>What is</label>
<input id="inputVal" name="inputVal" type="text" />
<br>
<label>The answer is</label>
<input name="outputVal" id="outputVal" type="text" />
<br>
<button class = "button" onclick="buttonPressed()">Check my Answer</button>
</form>
Your if statement is invalid:
function buttonPressed() {
var userAnswer = document.getElementById("outputVal").value;
if (answer === userAnswer) {
alert("Correct- Well Done!");
}
Because "answer" is not a variable, it's a value returned by the function "genAnswer".
So your "if" statement should go like this:
If(genAnswer() == userAnswer){}

Javascript random generator

I created a random number generator in javascript whose values are in an array.
The code is that one
function GetValue()
{
var names= new Array(1,2,3,4,5);
var random = names[Math.floor(Math.random() * names.length)];
//alert(random);
document.getElementById("message").innerHTML=random;
}
<p>number generator</p>
<form class="form">
<div class="form-group">
<input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default" />
<p id="message"></p>
</div>
</form>
I'd like to know if it is possible to give a different text in the p tag according to the number generated by the button.
Thanks very much and sorry if there is any english error
Just give the element an identifier, select it in your code and change the value according to your 'random' value:
function GetValue() {
var names = [1,2,3,4,5];
var random = names[Math.floor(Math.random() * names.length)];
var messageContainer = document.getElementById("message");
var headline = document.getElementById("headline");
if (random <= 2) {
headline.innerHTML = 'Hamburger (' + random + ')';
} else {
headline.innerHTML = 'Fish (' + random + ')';
}
}
<p id="headline">number generator</p>
<form class="form">
<div class="form-group">
<input type="button" id="btnSearch" value="Generatore" onclick="GetValue();" class="btn btn-default"/>
<p id="message"></p>
</div>
</form>
I'm not sure of what you want, but If you want to randomly select from a string:
function GetValue(){
var names= new Array(1,2,3,4,5);
var texts = ["foo", "bar", "baz", "foo2", "barbaz"];
var random = names[Math.floor(Math.random() * names.length)];
//alert(random);
document.getElementById("message").innerHTML = texts[random - 1];
};
here is the fiddle: https://jsfiddle.net/x2zkph3x/
If your question is "How to display a randomly selected text when clicking a button", this is the answer:
var generator = document.getElementById('generator'),
message = document.getElementById('message'),
strings = ['first', 'second', 'third'];
generator.addEventListener('click', function(event) {
message.textContent = strings[Math.random() * strings.length | 0];
});
<input type="button" id="generator" value="Generate">
<p id="message"></p>

Categories

Resources