Simple calc in javascript not woriking as it should - javascript

I made some simple functions in javaScript. But when I print the result I get the correct results for multiplication and division but not addition and subtraction.
Why is that, the functions are almost identitcal.
<script type="text/javascript">
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 addition() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("firstNumber").value;
document.getElementById("result").innerHTML = num1 + num2;
}
function subtract() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("firstNumber").value;
document.getElementById("result").innerHTML = num1 - num2;
}
</script>
<body>
<form>
<p>1st Number: <input type="text" id="firstNumber" /><br></p>
<p>2nd Number: <input type="text" id="secondNumber" /><br></p>
<input type="button" class="btn btn-success" onClick="multiplyBy()" Value="Multiply" />
<input type="button" class="btn btn-warning" onClick="divideBy()" Value="Divide" />
<input type="button" class="btn btn-danger" onClick="addition()" Value="Add" />
<input type="button" class="btn btn-primary" onClick="subtract()" Value="Subtract" />
</form>
<br/>
<p>The Result is : <br/>
<span id = "result"></span>
</p>
</body>

change
function addition() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("firstNumber").value;
document.getElementById("result").innerHTML = num1 + num2;
}
function subtract() {
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("firstNumber").value;
document.getElementById("result").innerHTML = num1 - num2;
}
to
function addition() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = (num1 + num2);
}
function subtract() {
num1 = parseInt(document.getElementById("firstNumber").value);
num2 = parseInt(document.getElementById("secondNumber").value);
document.getElementById("result").innerHTML = (num1 - num2);
}
three things, parse input as number, use the correct id for num2 and do calculation in brackets to be safe

You have a typo in your addition/subtraction functions. You're getting 'firstNumber' in both! Oh the little things... ;-)
And you might also try the parseInt(), parseFloat() functions mentioned in a previous comment to ensure you are dealing with the correct data type.

Related

I started learning JavaScript and I have a problem with if statement

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>

basic calculator created in javascript.. use an alert to tell user about any errors. the possible errors include:

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.

JavaScript regarding string and integer value

i need to help to learn this. Thanks in advance.
<label>Value 1</label> <input type="text" id="value1" name="value1" /><br />
<script>
var num1 = document.getElementById("value1");
parseInt(num1.value) // this gives an integer when you key in an integer in the input box.
var num1 = document.getElementById("value1").value;
parseInt(num1) // this gives NaN when you key in an integer in the input box.
</script>
May i know why is there a difference between them? I thought that they are the same but it's not.
From your new post (You posted as an answer, which is deleted now), You are trying to get the value from the input field before the values are inserted.
Move these lines to inside function add, so that value as assigned to variables only after clicking the button.
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
The function should be like
function add () {
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
var sumup = parseInt(num1.value) + parseInt(num2.value);
document.getElementById("output").innerHTML = "The total is " + sumup;
}
And the answer for your question is there is no difference between
var num1 = document.getElementById("value1");
parseInt(num1.value)
and
var num1 = document.getElementById("value1").value;
parseInt(num1)
Check the snippet below
<form action="" name="add1">
<label>Value 1</label>
<input type="text" id="value1" name="value1" />
<br />
<label>Value 2</label>
<input type="text" id="value2" name="value2" />
<br />
<br />
<div id="output"></div>
<br />
<button type="button" id="addup">Add</button>
</form>
<script>
document.getElementById("addup").addEventListener("click", add);
function add() {
var num1 = document.getElementById("value1").value;
var num2 = document.getElementById("value2").value;
var sumup = parseInt(num1) + parseInt(num2);
document.getElementById("output").innerHTML = "The total is " + sumup;
}
</script>
Both examples seem equivalent, something else is wrong. Maybe you are overwriting num1 variable? Try this:
var num1 = document.getElementById("value1");
parseInt(num1.value) // this gives an integer when you key in an integer in the input box.
var num2 = document.getElementById("value1").value;
parseInt(num2) // this gives NaN when you key in an integer in the input box.

Why doesn't this simple HTML/JavaScript calculator work?

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;
}

Select operation in simple calculator not working?

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);.

Categories