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>
Related
I am stuck here with duch issue. There are 2 two entry boxes are for an amount and an interest rate (%).
If you click on the button, the page will show an overview of the balance until the amount have to be doubled.
Taking a simple numbers forexample 10 - is amount and 4 - is 4% intereste rate. So the result have to stop on amount of 20.
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = 1; i <= doubleS; i++) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
The issue is with your for loop bounds.
This will loop doubleX number of times: for (var i = 0; i < doubleX; i++)
This will loop until x surpasses doubleX: for (;x < doubleX;), which btw is better written with a while loop: while (x < doubleX)
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
result.innerHTML = '';
while (s < doubleS) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
}
}
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
Easiest way is to just use a for loop without the convoluted math with s in the middle:
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
for (var i = s; i <= doubleS; i *= ((r / 100) + 1)) {
result.innerHTML += i + "<br>";
}
}
use a while loop and check is the value of s is bigger than or equal to doubleS
document.getElementById("button").onclick = loop;
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var result = document.getElementById("result")
function loop() {
var s = inputB.value;
var r = inputC.value;
var doubleS = s * 2;
while(true) {
s = ((r / 100 + 1) * s);
result.innerHTML += s + "<br>";
if(s >= doubleS){
break
}
}
}
<! DOCTYPE html>
<html>
<body>
<br>
<input type="text" id="inputB" value="10"><br>
<input type="text" id="inputC" value="4"><br><br>
<button id="button">Klik</button>
<p> De ingevoerde resultaten: </p>
<p id="result"></p>
<script async src="oefin1.js"></script>
</body>
</html>
I created a function that calculates the final cost of an order, and I'm trying to display it in a text box. However, the text box keeps returning "$ NaN" and I cannot find the error. I'm a very beginning student of html and js, so any explanation is appreciated.
function costCalculator() {
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value= "$ "+parseFloat(this.totalCost).toFixed(2);
document.getElementById("balance").value= "$ "+parseFloat(this.balance).toFixed(2);
}
Here's the button that calls the function and the text box that I want it to appear it:
<button id="totalSales" onclick = "costCalculator();" >Calculate Total</button>
<br><br>
<input type="text" id="finalCost" value="" size="3" readonly="true" />
You should check console log or run debugger (F12) first - lot of bugs / missing info at least in question here, but in case I put something instead of all missing items, it starts to run without code errors at least ;-)
var burgerOnePrice = 123,
burgerTwoPrice = 234,
burgerThreePrice = 345,
tip = 456,
useCard = 1;
function costCalculator() {
var totalCost = 0,
f = document.forms[0],
balance = { value: f.balance.value.replace(/[$ ]/,'') },
burgerOne = f.burgerOne,
burgerTwo = f.burgerTwo,
burgerThree = f.burgerThree;
totalCost = (totalCost + burgerOnePrice * Number(burgerOne.value));
totalCost = (totalCost + burgerTwoPrice * Number(burgerTwo.value));
totalCost = (totalCost + burgerThreePrice * Number(burgerThree.value));
totalCost = totalCost * (1 + tip);
if (useCard == 1) {
if (Number(balance.value) >= totalCost) {
totalCost = 0;
cardBalance = cardBalance - totalCost;
balance.value = cardBalance;
f.finalCost.value = totalCost;
} else {
totalCost = (totalCost - Number(balance.value));
balance.value = 0;
f.finalCost.value = totalCost;
}
}
document.getElementById("finalCost").value = "$ " + parseFloat(totalCost).toFixed(2);
document.getElementById("balance").value = "$ " + parseFloat(balance.value).toFixed(2);
}
<form>
<input type="button" id="totalSales" onclick = "costCalculator();" value="Calculate Total">
<br><br>
<input name="burgerOne" value="1">
<input name="burgerTwo" value="2">
<input name="burgerThree" value="3">
<input type="text" id="finalCost" value="" size="3" readonly="true" />
<input id="balance" value="$ 100000">
</form>
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.
I am trying to take two numbers from html and using javascript return sum of both but my num1 and num2 contains HTMLInputElement??
html:
<head>
<script type ="text/javascript" src="functions.js"></script>
</head>
<body>
Value 1: <input type="text" id="tb1" name="tb1"><br/>
Value 2: <input type="text" id="tb2" name="tb2"><br/>
Result: <input type="text" id="tb3" name="tb3"><br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
</body>
javascript:
function validateForm() {
var x = document.getElementById("tb1");
var y = document.getElementById("tb2");
if (x == null || x == "" || y == null || y == "")
{
alert("Value cannot be empty");
return false;
}
else {
//myAdd(x,y);
alert(x + y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").innerHTML = total;
}
}
You are not parsing and adding values from those two inputs, but objects itself. Because of that your if statement block would never run, as you are comparing object to null.Also and you can't set innerHTML of an input,have to use .value.Check the snippet below
parseFloat(x) //you must parseFloat(x.value),
document.getElementById("tb3").value = total; //you have to use .value instead of .innerHTML with input
function validateForm() {
var x = document.getElementById("tb1").value;
var y = document.getElementById("tb2").value;
if (x == null || x === "" || y == null || y === "") {
alert("Value cannot be empty");
return false;
} else {
//myAdd(x,y);
var num1 = parseFloat(x);
var num2 = parseFloat(y);
var total = num1 + num2;
document.getElementById("tb3").value = total;
}
}
Value 1:
<input type="text" id="tb1" name="tb1">
<br/>Value 2:
<input type="text" id="tb2" name="tb2">
<br/>Result:
<input type="text" id="tb3" name="tb3">
<br/>
<button onclick="validateForm()" Type="button" id="b1" name="b1">Go</button>
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;
}