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

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

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.

Simple calc in javascript not woriking as it should

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.

Getting unexpected result when changing from innerHTML to form, input type text Field

When I tested my code using innerHTML gave var num1=57; got correct result 73.375, now when change code to use a form with input type text box when entering number 57 it changes expected result to 629.625.. any help with this would be appreciated
<!DOCTYPE html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<link rel="style" href="css/main.css" type"text/css"/>
<title> Get final width </title>
<script type= "text/javascript">
function sum()
{
var num1;
num1= document.getvalue.width.value;
var acc1 = (num1 + 0.625)/(6.25-0.5);
var acc2 = Math.ceil((acc1 * 10) / 10) * 6.25 + (4.125 + 0.5);
document.getElementById('finalwidth').value = (acc2).toFixed(3);
document.getElementById("finalwidth").readOnly=true;
}
</script>
</head>
<body>
<div>
<h3> when input is 57 final width result should be : 73.375</h3>
<h3> when input is 100 final width result should be : 117.125</h3>
</div>
<form name= "getvalue">
<label for="width"> Width: </label>
<input type="text" name="width" maxlength="5" size="10" value=""/>
<input type="button" name="button" Value="calculate" onclick="sum()"/>
<label for="finalwidth"> Final width: </label>
<input type="text" id="finalwidth" name="finalwidth" maxlength="4" size="10" value=""/>
</form>
</body>
Try this out:- http://jsfiddle.net/adiioo7/6q8u5/1/
JS:-
function sum() {
var num1;
num1 = parseInt(document.getvalue.width.value);
var acc1 = (num1 + 0.625) / (6.25 - 0.5);
var acc2 = Math.ceil((acc1 * 10) / 10) * 6.25 + (4.125 + 0.5);
document.getElementById('finalwidth').value = (acc2).toFixed(3);
document.getElementById("finalwidth").readOnly = true;
}
When you do:
num1 = document.getvalue.width.value;
the value of num1 is a string (since form control values are always strings). So when you do:
num1 + 0.625
the values are concatenated as strings, not added as numbers. So if the value of num1 is say 57, then the result of the above expression will be the string 570.625. Because other arithmetic operations are conducted, the final result of:
(num1 + 0.625)/(6.25 - 0.5)
will be a number.
The simple fix is to convert num1 to a number using the unary + operator:
var num1 = +document.getvalue.width.value;
or
var acc1 = (+num1 + 0.625)/(6.25 - 0.5)
You can also be more explicit and use Number as a function:
var num1 = Number(document.getvalue.width.value);

Categories