Javascript Calculator only returns undefined [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Please help. I am working on a simple Javascript Calculator. It will only return undefined. Ive looked over the code multiple times. I dont believe it is a typo error, but i cant seem to figue it out any help would be greatly appreciated.
function calc(a,b,op) {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add"){
calculate == a + b;
}else if (op =="min"){
calculate == a - b;
}else if (op =="mult"){
calculate == a * b;
}else if (op =="div"){
calculate == a / b;
}
document.querySelector("#results").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
Operator: <select name="" id="operator">
<option value="add">Add</option>
<option value="min">Subtract</option>
<option value="mult">Multiply</option>
<option value="div">Divide</option>
</select>
Value 2: <input type="text" id="value2">
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="results"></div>
</body>
<script src="hello.js"></script>
</html>

calculate == a + b;
You only need a single =;
It should be
if (op == "add"){
calculate = a + b;
}else if (op =="min"){
calculate = a - b;
}else if (op =="mult"){
calculate = a * b;
}else if (op =="div"){
calculate = a / b;
}

It's a simple typo
= is assignment
== is equality check
change calculate == to calculate =

== is for comparison. You need assignment in your if branches, which is =.
Also, nothing is allowed between </body> and </html>. Your script element should be just prior to the closing body tag.
Finally, don't use .innerHTML if you can avoid it (which you almost always can) as it has security and performance implications. Since you aren't working with an HTML string anyway, use .textContent.
function calc(a,b,op) {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add"){ // <-- Compare here with ==
calculate = a + b; // Assign here with =
}else if (op =="min"){
calculate = a - b;
}else if (op =="mult"){
calculate = a * b;
}else if (op =="div"){
calculate = a / b;
}
document.querySelector("#results").textContent = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
Operator: <select name="" id="operator">
<option value="add">Add</option>
<option value="min">Subtract</option>
<option value="mult">Multiply</option>
<option value="div">Divide</option>
</select>
Value 2: <input type="text" id="value2">
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="results"></div>
<!-- Script should be here -->
<script src="hello.js"></script>
</body>
</html>

You were assigning two times, calculate == a + b; instead of calculate = a + b;
function calc(a,b,op) {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op === "add") {
calculate = a + b;
} else if (op === "min") {
calculate = a - b;
} else if (op === "mult") {
calculate = a * b;
} else if (op === "div") {
calculate = a / b;
}
document.querySelector("#results").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
Operator: <select name="" id="operator">
<option value="add">Add</option>
<option value="min">Subtract</option>
<option value="mult">Multiply</option>
<option value="div">Divide</option>
</select>
Value 2: <input type="text" id="value2">
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="results"></div>
</body>
<script src="hello.js"></script>
</html>

function calc() {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate=0;
console.log(a+" "+b+" "+op)
if (op == "add"){
calculate = a + b;
console.log(calculate)
}else if (op =="min"){
calculate = a - b;
}else if (op =="mult"){
calculate = a * b;
}else if (op =="div"){
calculate = a / b;
}
document.querySelector("#results").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
Operator: <select name="" id="operator">
<option value="add">Add</option>
<option value="min">Subtract</option>
<option value="mult">Multiply</option>
<option value="div">Divide</option>
</select>
Value 2: <input type="text" id="value2">
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="results"></div>
</body>
<script src="hello.js"></script>
</html>

Related

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output.
Here is my code:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = document.getElementById('userInput').value;
if (input == randomNumber) {
alert.innerHTML = "Your guess is right " + "," + ",it was " + randomNumber;
} else if (number > randomNumber && input < 10) {
alert.innerHTML = "Your guess is to high";
} else if (input < randomNumber && input > 1) {
alert.innerHTML = "Your guess is too low ";
} else if (isNaN(input)) {
alert.innerHTML = "Invalid operator";
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
}
Here it the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<script src="script.js">
</script>
</body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="aginButton">Try again</button>
</div>
</html>
There a couple of issues in your code, first in the html code, you got the id of again button wrong, it should be like this:
<button id="againButton">Try again</button>
Then in the JS code, you should move the two addEventListener() methods out of the checkNumber() function definition. Most importantly, you set the input variable to be the value of the input html element. The value property returns string, and then you compare randomNumber with a string which will not work as expected.
Also, the alert.innerHTML will not work. alert() is a global method which will accepts a string type as its parameter. Please see the JS code corrected below:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = parseInt(document.getElementById('userInput').value);
if (input === randomNumber) {
window.alert("Your guess is right it was " + randomNumber)
} else if (input > randomNumber && input < 10) {
window.alert("Your guess is to high");
} else if (input < randomNumber && input > 1) {
window.alert("Your guess is too low ");
} else if (isNaN(input)) {
window.alert("Invalid operator");
}
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
You should also put your script tag right before the ending </body> tag for it to be able to do its tasks on the DOM elements. Take a look here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="againButton">Try again</button>
</div>
<script src="script.js"></script>
</body>
</html>
There were a few errors in your script. Check out this fixed version.
UPDATE
I now put the <script> element ahead of the <body> element to demonstrate the necessitiy of the window.onload=function(){...}. My whole script is now placed within this function as otherwise, the DOM elements the script refers to, would not yet exist.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
<script>
window.onload=function(){
const [form1,againButton,output,inp]="container,againButton,outputText,userInput".split(",")
.map(id=>document.getElementById(id)), setrndm=_=>randomNumber=Math.ceil(Math.random()*10);
var randomNumber;
setrndm();
form1.addEventListener('submit', checkNumber);
againButton.addEventListener('click', setrndm);
function checkNumber(ev) {
ev.preventDefault(); inp.select();
var input = inp.value;
if (input == randomNumber) {
console.log("Your guess is right, it was " + randomNumber);
} else if (input > randomNumber && input < 11) {
console.log("Your guess is to high");
} else if (input < randomNumber && input > 0) {
console.log("Your guess is too low ");
} else if (isNaN(input)) {
console.log("Invalid operator");
}
}
};
</script>
</head>
<body>
<form id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button type="button" id="againButton">Try again</button>
</form>
</body>

Custom function does not read values from input [duplicate]

This question already has answers here:
Javascript function passing
(5 answers)
Closed 1 year ago.
I am attempting to create a calculator like thing. I have a custom function that is suppose to load input value from two variables and them put them together but it did not work, so I checked with console log if it loads the input value, and all it says is that the values are undefined. Any idea how to fix this please?
let num1 = document.getElementById("number1").value,
num2 = document.getElementById("number2").value,
operator = document.getElementById("select"),
resolutor = document.getElementById("resolute"),
res = document.getElementById("result");
function mathoperation(num1, num2) {
let value = operator.value,
result;
switch (value) {
case "plus":
console.log(num1); //console says unindefied
console.log(num2); //console says unindefied
break;
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Úloha 18.1</title>
</head>
<body>
<input type="text" id="number1">
<select name="" id="select">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="krat">*</option>
<option value="deleno">/</option>
</select>
<input type="text" id="number2">
<input type="button" id="resolute" value="=" onclick="mathoperation()">
<input type="text" id="result" readonly>
</body>
</html>
You have to get value of input element inside of your click event handler because you need those values at the moment you click it
function mathoperation() {
let num1 = document.getElementById("number1").value,
num2 = document.getElementById("number2").value,
operator = document.getElementById("select"),
resolutor = document.getElementById("resolute"),
res = document.getElementById("result");
let operatorValue = operator.value;
switch (operatorValue) {
case "plus":
let result = Number(num1) + Number(num2);
res.value = result;
console.log(num1); //console says unindefied
console.log(num2); //console says unindefied
break;
}
}
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Úloha 18.1</title>
</head>
<body>
<input type="text" id="number1">
<select name="" id="select">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="krat">*</option>
<option value="deleno">/</option>
</select>
<input type="text" id="number2">
<input type="button" id="resolute" value="=" onclick="mathoperation()">
<input type="text" id="result" readonly>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Úloha 18.1</title>
</head>
<body>
<input type="text" id="number1">
<select name="" id="select">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="krat">*</option>
<option value="deleno">/</option>
</select>
<input type="text" id="number2">
<input type="button" id="resolute" value="=" onclick="mathoperation()">
<input type="text" id="result" readonly>
<script>
function mathoperation(num1, num2) {
var num1 = document.getElementById("number1").value;
var num2 = document.getElementById("number2").value;
var operator = document.getElementById("select");
var resolutor = document.getElementById("resolute");
var res = document.getElementById("result");
let
value = operator.value,
result;
switch (value) {
case "plus":
res.value = parseInt(num1)+parseInt(num2);
break;
}
}
</script>
</body>
</html>
Moving your assignment inside the function can solve this.
This should get you started-
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Úloha 18.1</title>
</head>
<body>
<input type="text" id="number1">
<select name="" id="select">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="krat">*</option>
<option value="deleno">/</option>
</select>
<input type="text" id="number2">
<input type="button" id="resolute" value="=" onclick="mathoperation()">
<input type="text" id="result" readonly>
<script>
function mathoperation(num1, num2) {
var num1 = document.getElementById("number1").value;
var num2 = document.getElementById("number2").value;
var operator = document.getElementById("select");
var resolutor = document.getElementById("resolute");
var res = document.getElementById("result");
let
value = operator.value,
result;
switch (value) {
case "plus":
res.value = parseInt(num1)+parseInt(num2);
break;
}
}
</script>
</body>
</html>

How to show all steps in a while loop

I'm working on a small project about the Collatz conjecture.
In this project i want to apply the formula " times 3 plus one" when the number is odd and devide a number when its even.
i want to keep looping this until the number is 1 and show not only how many steps it took but also display all the numbers it goes through.
i've gotten quite far i think but i have trouble displaying all the steps the loop goes through.
here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = (num * 3) + 1; /*odd*/
console.log(num) }
i++
document.getElementById('result').innerHTML = "Result is " + num + " found in " + i + " runs";
}
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small><input type="text" id="num" name="num" min="0" /><input type="button" value="submit"
onclick="findOddEven()" name="find" />
<div style="margin-top: 10px;" id="result"></div>
</form>
</body>
</html>
You can store the numbers in the array and display them at the end. You can also move the .innerHTML out of the loop since this only needs to be done when the loop is finished.
I've used join to turn the array into a comma seperated string.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collatz Conjecture</title>
<script>
function findOddEven() {
var num = document.getElementById('num').value;
let steps = [num]; // Store starting number
let i = 0;
while (num != 1) {
if (num % 2 == 0) {
num = num / 2; /*even*/
} else {
num = num * 3 + 1; /*odd*/
}
steps.push(num); // Add changed number to the array
i++;
}
document.getElementById('result').innerHTML =
'Result is ' + num + ' found in ' + i + ' runs. Steps taken: ' + steps.join(', ');
}
</script>
</head>
<body>
<form method="post">
<small>Number:</small
><input type="text" id="num" name="num" min="0" /><input
type="button"
value="submit"
onclick="findOddEven()"
name="find"
/>
<div style="margin-top: 10px" id="result"></div>
</form>
</body>
</html>
Is your problem not seeing all numbers? If so, your console.log is inside the else statement. To see all numbers you shall move it outside the if else statement.

InnerHTML issue Calculator

Im working on a basic Calculator and keep having two errors involving innerHTML. I use the developer tools to debug.
The Developer tool says: Uncaught TypeError: Cannot set property 'innerHTML' of null # document.querySelector("#result").innerHTML = calculate;
also "button type="button" onclick="calc()">Calculate</button" is Highlighted green.
I am a codenewbie, have no idea were my mistake is
function calc() {
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);
var op = document.querySelector("#operator").value;
var calculate;
if (op == "add") {
calculate == a + b;
} else if (op == "min") {
calculate == a - b;
} else if (op == "mult") {
calculate == a * b;
} else if (op == "div") {
calculate == a / b;
}
document.querySelector("#result").innerHTML = calculate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello world</h1>
<form>
Value 1: <input type="text" id="value1"> Operator:
<select name="" id="operator">
<option value="add">Add</option>
<option value="min">Subtract</option>
<option value="mult">Multiply</option>
<option value="div">Divide</option>
</select>
Value 2: <input type="text" id="value2">
<button type="button" onclick="calc()">Calculate</button>
</form>
<div id="results"></div>
</body>
<script src="hello.js"></script>
</html>
The error is coming because in HTML u have given id results and in java script you are writing document.queryseletor('#result')
S is missing in java script

What's wrong with this calculation function?

I wrote everything correctly, but it's not working. I can't understand; I don't see a problem, but it still doesn't work. My English isn't very good, so I have trouble explaining in detail.
I just don't know why this doesn't work.
function calc() {
var a = parseInt(document.querySelector("#value1").value);
var a = parseInt(document.querySelector("#value2").value);
var op = (document.querySelector("#operator").value);
var calculate;
if (op == "add") {
calculate = a + b;
} else if (op =="min") {
calculate = a - b;
} else if (op =="div") {
calculate = a / b;
} else if (op =="mul") {
calculate = a * b;
}
console.log(calculate);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form>
Value 1: <input type="text" id="value1">
<br>
Value 2: <input type="text" id="value2">
Operator:
<select id="operator">
<option value="add">Add</option>
<option value="min">Minus</option>
<option value="div">Divide</option>
<option value="mul">Multiply</option>
</select>
<button type="button" onclick="calc()">Calculate</button>
</form>
</body>
<script src="js/main.js"></script>
</html>
You're missing to declare the var 'b' in line number 3. The correct code should be :
var a = parseInt(document.querySelector("#value1").value);
var b = parseInt(document.querySelector("#value2").value);

Categories

Resources