I made a simple Javascript/HTML calculator where you can input two digits and select an operation and it solves it
The problem is, it always prints "Answer: Undefined" and "Invalid Operation"
It worked until I added the select an operation (it was strictly addition then)
Here is my code
var back = 0;
var DoIt;
var operation = document.getElementById("Select").value;
function add(num1, num2) {
return num1 + num2;
}
function multiply(num1, num2) {
return num1 * num2;
}
function subtract(num1, num2) {
return num1 - num2;
}
function divide(num1, num2) {
return num1 / num2;
}
function functions() {
if (back==0)
{
var first = document.getElementById("number1").value;
var second = document.getElementById("number2").value;
first = parseInt(first);
second = parseInt(second);
if (operation=="Add"||operation=="add")
{
var DoIt = add(first, second);
}
else if (operation=="Subtract"||operation=="subtract")
{
DoIt = subtract(first, second);
}
else if (operation=="Multiply"||operation=="multiply")
{
DoIt = multiply(first, second);
}
else if (operation=="Divide"||operation=="divide")
{
DoIt = divide(first, second);
}
else
{
document.getElementById("Select").value = "Invalid Operation";
}
document.getElementById("number1").style.display = 'none';
document.getElementById("number2").style.display = 'none';
document.getElementById("Answer").style.display = 'block';
document.getElementById("Answer").value = "Answer: " + DoIt;
document.getElementById("write").value = "Go Back";
back = back+1;
}
else
{
document.getElementById("Answer").style.display = 'none';
document.getElementById("number1").style.display = 'inline';
document.getElementById("number2").style.display = 'inline';
document.getElementById("write").value = "Go";
back = 0;
}
}
HTML
<input id="Answer" placeholder="Answer" class="inputs">
<input id="number1" placeholder="First Number" class="inputs">
<br />
<input id="number2" placeholder="Second Number" class="inputs">
<br />
<input id="Select" placeholder="Choose An Operation" class="inputs">
<p id="Texts">Enter Add, Subtract, Multiply, or Divide.</p>
<input type="button" id="write" onclick="functions();" value="Go" class="button">
You have to declare the variables operation and DoIt inside the function functions():
function functions(){
var operation = document.getElementById("Select").value;
var DoIt;
if (back==0)
// the rest of the function
}
And you shouldn’t declare the variable DoIt twice. So the line var DoIt = add(first, second); should become DoIt = add(first, second);.
Related
function multiply() {
const num1 = document.getElementById("number_1").value;
const num2 = document.getElementById("number_2").value;
if (result > 1000) {
document.getElementById("result").innerText= "Nu blev det för högt";
} else if (result) {
document.getElementById("result").innerHTML = num1 * num2;
} else if (result < -0) {
document.getElementById("result").innerText= "Nu blev det för högt";
}
}
<input type="text" id="number_1" value="" size="5"/> *
<input type="text" id="number_2" value="" size="5"/> = <span id="result"></span>
<input onclick="multiply()" value="Beräkna" type="button"/>
If the answer is higher than 1000 or lower than -0 I want a message in the span to say that it's wrong. What in the code is wrong?
Assign a value to result first, then move the second condition up one level. Have the result the last.
function multiply() {
const num1 = document.getElementById("number_1").value;
const num2 = document.getElementById("number_2").value;
const result = num1 * num2;
if (result > 1000) {
document.getElementById("result").innerText= "Nu blev det för högt";
} else if (result < -1) {
document.getElementById("result").innerText= "Nu blev det för högt";
} else if (result) {
document.getElementById("result").innerHTML = result;
}
}
<input type="text" id="number_1" value="" size="5"/> *
<input type="text" id="number_2" value="" size="5"/> = <span id="result"></span>
<input onclick="multiply()" value="Beräkna" type="button"/>
I think you're missing the line
result = num1 * num2
Apart from the result variable absence there are some logical flaws in your code. There cannot be -0 ( 0 is neither positive nor negative), also in the second else if block you are just using result without any condition so the control will never reach the last else if block because a positive or negative value is always true in javascript.
Please fix these issues and repost the question if possible
2 issues: the lack of a result definition and the bad if statement.
The below code is fixed and commented to explain.
function multiply() {
const num1 = document.getElementById("number_1").value;
const num2 = document.getElementById("number_2").value;
const result = num1 * num2; // NEW
if (result > 1000) {
document.getElementById("result").innerText= "Nu blev det för högt";
} else if (result < -0) {
document.getElementById("result").innerText= "Nu blev det för högt";
} else {
document.getElementById("result").innerHTML = num1 * num2; // MOVED
}
}
<input type="text" id="number_1" value="" size="5"/> *
<input type="text" id="number_2" value="" size="5"/> = <span id="result"></span>
<input onclick="multiply()" value="Beräkna" type="button"/>
I started learning JavaScript and I want to do my own small project 'BMI calculator' but I can't find an error with my if statement.
Everything working fine but if as a input I will type for example 0, I don't see any warning message instead I see result of calculation.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input id="height">
<br> Weight: <input id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
Because you don't stop the function when you detect invalid input. You put the error message into the message panel, but then you continue to the code that performs the calculation with the invalid input.
You should return from the function after displaying the error message.
function sum() {
var num1 = +document.getElementById('height').value;
if (num1 <= 0) {
var text1 = " Wrong Height Input "
document.getElementById('messagePanel').innerHTML = text1;
return;
}
var num2 = +document.getElementById('weight').value;
if (num2 <= 0) {
var text2 = " Wrong Weight Input "
document.getElementById('messagePanel').innerHTML = text2;
return;
}
var num1 = num1 / 100;
var sum = num2 / (num1 * num1);
var fixedSum = sum.toFixed(1);
document.getElementById('messagePanel').innerHTML = fixedSum;
}
Height: <input type="number" id="height">
<br> Weight: <input type="number" id="weight">
<br>
<input type="button" value="Calculate" onclick="sum()">
<br> BMI:
<div id="messagePanel"></div>
I've created a basic 4 function calculator in JavaScript and now I need to use an alert to tell the user about any errors. the possible errors are:
One or both input fields are blank
One or both input fields < -9999 or greater than 9999
Divide by zero
Illegal character in either input field. Only 0, 1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9, and – are allowed.
Code:
function multiplyBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
document.getElementById("result").innerHTML = num1 / num2;
}
function additionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 + num2;
}
function subtractionBy() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = num1 - num2;
}
body {
margin: 30px;
}
<!DOCTYPE html>
<html>
<head>
<body>
<form>
1st Number : <input type="text" id="firstNumber"> 2nd Number: <input type="text" id="secondNumber"> The Result is :
<span id="result"></span>
<br>
</br>
<br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
<input type="button" onClick="additionBy()" Value="Add" />
<input type="button" onClick="subtractionBy()" Value="Sub" />
</br>
</form>
<script type="text/javascript" src="fourth.js">
</script>
</body>
</html>
first of all define the input tag type as number like below
1st Number : <input type="number" id="firstNumber" >
2nd Number: <input type="number" id="secondNumber" >
so, in that case user will not be able to enter invalid input.
secondly, check the divide by zero condition into the function only
There are libraries for validation that you can get but lets start simple. Rework what you have to remove duplicated code and then add functions to do your validation.
This is JUST A START not a complete solution, you have to do work. I will leave it to you to add the OTHER validation you need, but you can see how this is doing it with the couple I added.
function showResults(results) {
document.getElementById("result").innerHTML = results;
}
function multiplyBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 * num2);
}
function divideBy(number1, number2) {
num1 = number1.value;
num2 = number2.value;
showResults(num1 / num2);
}
function additionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 + num2);
}
function subtractionBy(number1, number2) {
num1 = parseInt(number1.value, 10);
num2 = parseInt(number2.value, 10);
showResults(num1 - num2);
}
function actionClicker() {
let number1 = document.getElementById("firstNumber");
let number2 = document.getElementById("secondNumber");
validateNumber(number1);
validateNumber(number2);
var attribute = this.getAttribute("data-myattribute");
var expr = attribute;
switch (expr) {
case 'multiply':
multiplyBy(number1, number2);
break;
case 'division':
divideBy(number1, number2);
break;
case 'subtract':
subtractionBy(number1, number2);
break;
case 'addition':
additionBy(number1, number2);
break;
default:
console.log('Sorry, we do not find ' + expr + '.');
}
}
function showValidationMessage(message) {
alert(message);
}
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function isEmpty(n) {
return n === "";
}
function isInRange(n) {
if (isNumeric(n) && !isEmpty(n)) {
num = parseInt(n, 10);
return num >= -9999 && num <= 9999;
}
return false;
}
function validateNumber(el) {
let hasError = false;
el.classList.remove("has-error");
// add your validation
let message = "get stuff better";
if (!isNumeric(el.value)) {
message = "Not a number.";
hasError = true;
}
if (isEmpty(el.value)) {
message = "Not a number, cannot be empty.";
hasError = true;
}
if (hasError) {
el.classList.add("has-error");
showValidationMessage(message);
}
}
function modifyNumbers(event) {
let el = event.target;
validateNumber(el);
}
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var buttons = document.getElementsByClassName('actions');
// add event listener to buttons
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', actionClicker, false);
}
num1.addEventListener("change", modifyNumbers, false);
num2.addEventListener("change", modifyNumbers, false);
body {
margin: 30px;
}
.buttons {
margin: 2em;
}
label {
padding-right: 1em;
padding-left: 1em
}
.has-error {
background-color: lightpink;
border: solid red 1px;
}
.numbers {
width: 11em;
}
<body>
<form>
<label for="firstNumber">1st Number:</label><input class="numbers" type="number" id="firstNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span><label for="secondNumber">2nd Number:</label><input class="numbers"
type="number" id="secondNumber" placeholder="Min: -9999, max: 9999" min="-9999" max="9999" /><span class="validity"></span>
<div><label>The Result is:</label>
<div id="result"></div>
</div>
<div class="buttons">
<button type="button" class="actions" id="multiply" data-myattribute="multiply">Multiply</button>
<button type="button" class="actions" id="divide" data-myattribute="division">Divide</button>
<button type="button" class="actions" id="add" data-myattribute="addition">Add</button>
<button type="button" class="actions" id="subtract" data-myattribute="subtract">Sub</button>
</div>
</form>
</body>
What you are looking for is a validation pattern.
To check if the inputs are valid you can perform checks at the beginning of your math functions. For example
var $num1 = document.getElementById("firstNumber");
var $num2 = document.getElementById("secondNumber");
var $result = document.getElementById("result");
function checkValid(division){
var num1 = $num1.value;
var num2 = $num2.value;
if(num1 == null || num1 > 9999 || num1 < -9999){
return false;
}
if(num2 == null || num2 > 9999 || num2 < -9999){
return false;
}
if(division && num2 === 0){
return false
}
}
function multiplyBy() {
if(check()){
num1 = $num1.value;
num2 = $num2.value;
$result.innerHTML = num1 * num2;
} else {
alert('some error message');
}
}
then in your division function call check(true)
This is just one way to handle it. You could call alert in the check function before returning or even return your error messages from the check function. This should get going in the right direction.
Also I do recommend the <input type="number"> changes by Hasan as well.
Here is my code:
<!DOCTYPE html>
<html>
<header></header>
<body>
<label id="FirstNumber">First Number:</label>
<input type="text" id="number1">
<br>
<label id="SecondNumber">Second Number:</label>
<input type="text" id="number2">
<br>
<button id="add" onclick="add()">Add</button>
<button id="multiply" onclick="multiply()">Multiply</button>
<br>
<label id="FinalNumberLabel">Answer:</label>
<label id="Answer"></label>
<script type="text/javascript">
function add() {
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
var answer = num1 + num2;
document.getElementById("Answer").innerHTML = answer;
}
function multiply() {
var num1 = document.getElementById("number1");
var num2 = document.getElementById("number2");
var answer = num1 * num2;
document.getElementById("Answer").innerHTML = answer;
}
</script>
</body>
</html>
The "Multiply" button returns a "NaN" error and the Add button always returns "[objectHTMLInputElement][objectHTMLInputElement]"
Why doesn't this work?
You're not getting the values, just the elements:
var num1 = document.getElementById("number1");
In this case num1 isn't actually a number, it's an objectHTMLInputElement.
You probably want to start with something like:
var num1 = parseFloat(document.getElementById("number1").value);
Perhaps also add some error checking, or specify that the inputs need to be numeric, etc.
.value -> you do not want the input element, you want the value it holds
parseInt -> you want number not string (or parseFloat if you want floats)
function add() {
var num1 = parseInt(document.getElementById("number1").value);
var num2 = parseInt(document.getElementById("number2").value);
var answer = num1 + num2;
document.getElementById("Answer").innerHTML = answer;
}
function multiply() {
var num1 = parseInt(document.getElementById("number1").value);
var num2 = parseInt(document.getElementById("number2").value);
var answer = num1 * num2;
document.getElementById("Answer").innerHTML = answer;
}
Hi i have this code on my site`
<body>
<script>
function calcResult() {
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = calcResult;
}
</script>
<div>
Enter value 1
<input type="text" id="txt1" />
<br />Enter value 2
<input type="text" id="txt2" />
<br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test() {
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if (isNaN(n1) || isNaN(n2)) {
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload = function() {
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1
<input type="text" id="od1" />
<br />Enter value 2
<input type="text" id="od2" />
<br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
The problem is that first form isnt working and the second is working. On my site i want many of these calculator, but i dont know why is not working. I will be gradefull if someone help me find result.
Write all javascript code in one script tag. Try the following code
<body>
<script>
function calcResult(){
document.getElementById('result').innerHTML = '';
var num1 = new Number(document.getElementById('txt1').value);
var num2 = new Number(document.getElementById('txt2').value);
if(isNaN(num1) || isNaN(num2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('result').innerHTML = num1 * num2;
}
}
function test(){
document.getElementById('re').innerHTML = '';
var n1 = new Number(document.getElementById('od1').value);
var n2 = new Number(document.getElementById('od2').value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById('re').innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = calcResult;
document.getElementById('od').onclick = test;
}
</script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
</body>
If both functions are equal (you just want to execute three diference elements),
use element's Ids as parameters in function argument and call it as often as you wish with any diference Id.
<body>
<script>
<div>
Enter value 1 <input type="text" id="txt1" /><br />
Enter value 2 <input type="text" id="txt2" /><br />
<button id="btnCalc">Calculate difference</button>
<div id="result"></div>
</div>
<script>
function test(id){
document.getElementById(id, id2, id3).innerHTML = '';
var n1 = new Number(document.getElementById(id2).value);
var n2 = new Number(document.getElementById(id3).value);
if(isNaN(n1) || isNaN(n2)){
alert('One or both inputs are not a number');
} else {
document.getElementById(id).innerHTML = n1 - n2;
}
}
window.onload=function(){
document.getElementById('btnCalc').onclick = function(){ test("result", "txt1", "txt2") };
document.getElementById('od').onclick = function(){ test("re", "od1", "od2") };
}
</script>
<div>
Enter value 1 <input type="text" id="od1" /><br />
Enter value 2 <input type="text" id="od2" /><br />
<button id="od">Calculate difference</button>
<div id="re"></div>
</div>
<script type="text/javascript">
function calcResult(resultId, valId, val2Id, operation) {
var $result = document.getElementById(resultId);
$result.innerHTML = '';
var num1 = new Number(document.getElementById(valId).value);
var num2 = new Number(document.getElementById(val2Id).value);
if (isNaN(num1) || isNaN(num2)) {
alert('One or both inputs are not a number');
} else {
$result.innerHTML = operation(num1, num2);
}
}
window.onload = function() {
document.getElementById('btnCalc').onclick = function() {
calcResult('result', 'txt1', 'txt2', function(num1, num2) {
return num1 * num2;
});
}
document.getElementById('od').onclick = function() {
calcResult('re', 'od1', 'od2', function(num1, num2) {
return num1 - num2;
});
};
}
</script>
Put all the scripts in one <script> tag.
Also, there's a room for improvement on your program. see below:
i can see that eventhough your button is named "calculate difference",
the first form is calculating the product and the second form is calculating the difference, thus, using this,
you can rewrite your code in such a way that you only have one function for both operations,
just pass the elementIds as parameters and a function which takes care which operation to apply. like the one I wrote above.
see it here: http://jsfiddle.net/1yo4ypc2/