JavaScript calculator writes wrong number - javascript

I have a small error in this code, please help me.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0,
maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
function calc() {
"use strict";
var price = document.getElementById('price').value;
var res = (price / 100 * 5 + 20) + price;
var show = document.getElementById('show').value = Math.floor(res);
}
</script>
</body>
</html>
ex:write 100 in input the result is 10025, I need 125

It's because you try to add String to a Number. You need to convert price to a Number like this :
var price = parseFloat(document.getElementById('price').value);
// Or like this :
var price = Number(document.getElementById('price').value);
// Or like this :
var price = document.getElementById('price').value * 1;
Full example which shows decimal numbers:
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
function calc() {
var price = parseFloat(priceElement.value, 10);
var result = (price / 100 * 5 + 20) + price;
showElement.innerHTML = result.toFixed(2);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>

Quite there.
A couple of fixes:
Store your elements outside of the function, since their ids won't change in your case:
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
Use parseFloat(...) to parse floating point numbers stored in strings:
var price = parseFloat(priceElement.value);
To set an element's content (in your case, the content of the h1 element), use .innerHTML:
showElement.innerHTML = Math.floor(result);
var priceElement = document.getElementById('price');
var showElement = document.getElementById('show');
function calc() {
var price = parseFloat(priceElement.value);
var result = (price / 100 * 5 + 20) + price;
showElement.innerHTML = Math.floor(result);
}
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>

Yes, the value of price is string, so convert it to number.
And I don't think your "document.getElementById('show').value" is useful.
And the variable show is not used.
And the formula for res is somewhat convoluted -- see var v1.
Maybe you will find using console.log's useful in debugging.
<html>
<body>
<input type="text" id="price">
<button onclick="calc()">GO</button>
<h1 id="show"></h1>
<script type="text/javascript">
"use strict";
function calc() {
var price = 1*document.getElementById('price').value;
console.log("price", price);
var res = (price / 100 * 5 + 20) + price;
console.log("res", res);
document.getElementById('show').innerHTML = Math.floor(res);
var v1 = price*1.05 + 20;
console.log("v1", v1);
document.getElementById('show').innerHTML += ", " + v1;
}
</script>
</body>
</html>

Related

Poll Percentages in JavaScropt

Its a simple poll app in Js. where user vote count and percentages will change accordingly. But the problem i am facing is the percentages are not updated, lets say total vote is 5 and yes vote is 3 among them so yes vote percentage should be updates as the no votes comes along but it not been updated automatically.
let count = document.getElementById('count')
let ncount = document.getElementById('ncount')
let num = 0;
let nnum = 0;
document.getElementById('btn').addEventListener('click', () => {
let nper = document.getElementById('per')
num++
let total = num + nnum
let totalPercentages = num / total * 100
count.innerHTML = num + " " + "percentages" + totalPercentages + '%'
nper.innerHTML = nnum + num + '<div></div>' + "total vote cast"
})
document.getElementById('Nbtn').addEventListener('click', () => {
let per = document.getElementById('per')
nnum++
let total = num + nnum
let totalPercentages = nnum / total * 100
ncount.innerHTML = nnum + " " + totalPercentages + '%'
per.innerHTML = num + nnum + '<div></div>' + "total vote cast"
})
<!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>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br></br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br></br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>
Using the event handlers as defined by the OP, the percentage updates can be handled in a separate function.
There are a few other updates to the code
statements should end with semicolons (;)
variables that are only assigned once should be declared with const
the <br> tag does not have a </br> closing tag
// const should be used for variables which are only assigned a value once
// every statement should end with a semicolon (;)
const count = document.getElementById('count');
const ncount = document.getElementById('ncount');
const per = document.getElementById('per');
let num = 0;
let nnum = 0;
// update the count, ncount and per displays
function updatePer() {
let total = num + nnum;
count.innerHTML = num + " percentages " + (num / total * 100) + '%';
ncount.innerHTML = nnum + " percentages " + (nnum / total * 100) + '%';
per.innerHTML = (nnum + num) + "<br>total vote cast";
}
// count each button click and call the updatePer function
document.getElementById('btn').addEventListener('click', () => {
num++;
updatePer();
})
document.getElementById('Nbtn').addEventListener('click', () => {
nnum++;
updatePer();
})
<!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>
<fieldset>
<legend>do you like pizza</legend>
<div id="count"> 0</div>
<button id="btn">yes</button>
<br>
<div id="ncount"> 0</div>
<button id="Nbtn">no</button>
<br>
<div id="per"></div>
</fieldset>
<script src="main.js"></script>
</body>
</html>
const poll = document.getElementById("poll");
// counts is an object literal which has two properties - yes and no
// yes and no are objects with an element and a count value
// these are used to keep track of the counts and update the corresponding element
const counts = {
yes: {
el: document.getElementById('yes-count'),
value: 0
},
no: {
el: document.getElementById('no-count'),
value: 0
}
};
const percentage = document.getElementById("percentage");
// get all the clicks in the poll
poll.addEventListener("click", evt => {
// get the id of the button that was clicked
if (evt.target.tagName === "BUTTON") {
const id = evt.target.id;
// remove '-btn' from the id
const count = id.replace('-btn', '');
// make sure the id is a property name
if (typeof counts[count] === "object") {
// get the counts object
const counter = counts[count];
// update the counter
counter.value++;
// update the display
counter.el.textContent = counter.value;
// update the percentage
percentage.textContent = ((counts.yes.value / (counts.yes.value + counts.no.value) * 100.0)).toFixed(2) + '%';
}
}
});
<fieldset id="poll">
<legend>do you like pizza</legend>
<output id="yes-count"> 0</output>
<button id="yes-btn">yes</button>
<br>
<output id="no-count"> 0</output>
<button id="no-btn">no</button>
<br>
<p>Percentage of people that like pizza <output id="percentage"></output></p>
</fieldset>

How do I get the result of this this Random Numbers generated in Javascript? I mean so I can alert or send to console

This piece of javascript successfully generated random number but I'm having challenge in fetching the variable value so I can use it as desired. below is the working code:
let btn = document.querySelector('button');
let output = document.querySelector('#output');
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() * step1;
let result = Math.floor(step2) + min;
return result;
}
function createArrayOfNumbers(start, end){
let myArray = [];
for(let i = start; i <= end; i++) {
myArray.push(i);
}
return myArray;
}
let numbersArray = createArrayOfNumbers(1,10);
btn.addEventListener('click', () => {
if(numbersArray.length == 0){
output.innerText = 'No More Random Numbers';
return;
}
let randomIndex = getRandomNumber(0, numbersArray.length-1);
let randomNumber = numbersArray[randomIndex];
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
});
<!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>
<button>Generate</button>
<h1 id="output" style="text-align: center">Random Number</h1>
<script src="script.js"></script>
</body>
</html>
There are several ways of doing but the easiest would be to create a global variable outside the function and then when that random number is generated assign that number to that global variable you can write it like this:
var myvariable = 0;
let btn = document.querySelector('button');
let output = document.querySelector('#output');
//all of your code and then at the end
numbersArray.splice(randomIndex, 1)
output.innerText = randomNumber;
myvariable = randomNumber;
});
Now this variable is accessible outside the function. Hope that helps!

What is missing from my discount code to make this work? Am I missing a variable?

I thought I had everything correct and I still can't seem to figure out why the function isn't working out the way it is supposed to. I have this issue where the code is having a reference error but I'm not sure how to define the function. I also put it through the W3 validator but that's not telling me anything.
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase =
parseInt(document.getElementById('purchase').value);
var dayOfWeek = new Date().getDay();
var output = document.querySelector("#output");
let rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
let discount = purchase * rate;
return purchase - discount;
output.innerHTML = "$" + String(getDiscountedAmount(200));
}
</script>
Please enter your final price: <input type="text" id="purchase" size="5">
<br>
<button type="button" onclick="getDiscountedAmount(purchase)">discount?
</button>
<div id="output"></div>
</body>
</html>
The first line of your function already is wrong, you're trying to get a float number from nothing and you're overriding your input parameter to the function
var purchase = parseFloat();
Try:
purchase = parseFloat(purchase);
so that it uses your input parameter.
Also I'm not too sure about your date comparison dayOfWeek == (2, 3), I don't know if that works, I've never seen that before, I personally use [2, 3].includes(dayOfWeek)
And lastly your function returns a value but then you don't see that value anywhere, try using
console.log(getDiscountedAmount(200)) or whatever your price is
In terms of your input and output you want to use DOM manipulation to get the input and show the output.
If you want to see the value in your "output" then
var output = document.querySelector("#output");
output.innerHTML = "$" + String(getDiscountedAmount(200));
Would be a simple DOM mechanism, but it's not the cleanest
One more tip is to put your script tags lastly in the body, because you want all your HTML elements "defined" first before you try to access them
Altogether a cleaner version of your code:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
Please enter your final price: <input type="text" id="myInput" size="5" /><br />
<button type="button" id="myButton">discount?</button>
<div id="myOutput"></div>
<script>
var myInput = document.querySelector("#myInput");
var myOutput = document.querySelector("#myOutput");
var myButton = document.querySelector("#myButton");
myButton.onclick = function() {
// Computes and returns a discounted purchase amount.
var purchase = parseFloat(myInput.value);
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 1000) {
rate = 0.025;
} else {
rate = 0.03;
}
let discount = purchase * rate;
var finalPrice = purchase - discount;
output.innerHTML = "$" + String(finalPrice);
};
</script>
</body>
</html>
I changed around some ID's and moved the onclick into your JavaScript for cleaner code overall, as we like to separate the HTML from the JS
When you load your script you get an Uncaught SyntaxError because you closed your function with two }. To fix this just delete line 31.
In your first line of the function you are using parseFloat(); wrong:
var purchase = parseFloat();
Do:
var purchase = parseFloat(purchase);
Than you need to get your input number.
getDiscountedAmount(purchase) in the onclick event doesn't work.
You can use this:
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
In the end you have to do this to show the number in you output div:
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
Here is your code and how i fixed it:
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
<script>
/* Input: purchase amount
* Processing: determine through if statements if they get a discount
* Output: final price after tax
*/
// Computes and returns a discounted purchase amount.
function getDiscountedAmount(purchase) {
var purchase = document.getElementById("purchase").value; // get value from text field
purchase = parseFloat(purchase); // convert to float
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
}
else if (purchase < 100 && dayOfWeek ==(2,3)) {
rate = 0.06;
}
else if (purchase < 1000) {
rate = 0.025;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
document.getElementById("output").innerText = output; // set discont into your output div
return output;
}
</script>
</head>
<body>
Please enter your final price: <input type="text" id="purchase" size="5"><be>
<button type="button" onclick="getDiscountedAmount()">discount?</button>
<div id="output"></div>
</body>
</html>
I didn't change your return statement and dayOfWeek because i don't know how you exactly want to use it.
Here is what you are looking for:
body{margin:0;padding:0;font-family:arial;background:rgb(30,30,30);height:100vh;width:100%}.wrapper{background:lightgrey;background:linear-gradient(318deg,rgba(217,123,123,1) 0%,rgba(135,249,255,1) 100%);width:80%;height:126px;position:relative;top:calc(50vh - 63px);left:10%;padding:3px;border-radius:12px}.content{background:rgb(80,80,80);background:rgba(0,0,0,.5);border-radius:10px;width:calc(100% - 24px);padding:12px}label{font-weight:700;color:#fff}input{width:calc(100% - 16px);margin-top:4px;padding:6px;border:2px solid #fff;border:2px solid rgba(0,0,0,.3);color:#fff;background:#fff;background:rgba(0,0,0,.5);border-radius:6px;font-size:14pt}::placeholder{color:#fff;color:rgba(255,255,255,.8)}input:focus{outline:none;border:2px solid #fff;border:3px solid rgba(0,0,0,.6);padding:5px}.output-container{display:inline-block;float:right;width:180px;padding:8px;color:#fff;background:#fff;background:rgba(0,0,0,.5);font-size:12pt;margin-top:4px;border-radius:6px;font-size:14pt}button{margin-top:4px;width:150px;border:0;border-radius:6px;padding:8px;background:gray;background:rgba(0,0,0,.6);color:#fff;font-weight:700;font-size:14pt;transition:0.25s ease}button:focus{outline:none;}button:hover{cursor:pointer;background:gray;background:rgba(0,0,0,.8)}#media only screen and (max-width:400px){.wrapper{width:calc(100% - 6px);height:auto;top:0;left:0;border-radius:0}.output-container,button{width:calc(50% - 12px)}}
<!DOCTYPE HTML>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>discount amount</title>
</head>
<body>
<div class='wrapper'>
<div class='content'>
<label>Please enter your final price:</label><input type="text" autocomplete="off" placeholder='Enter price...' id="purchase" size="5">
<button type="button" onclick="getDiscountedAmount()">See discount</button>
<div class='output-container'>Total: <span id='output'>--</span></div>
</div>
</div>
<script>
//Get the output element
outputEl = document.getElementById("output");
function getDiscountedAmount() {
//Gets the value of your input
var purchase = parseFloat((document.getElementById('purchase').value).replace(/[^\d]/g,""));
var dayOfWeek = new Date().getDay();
var rate;
if (purchase < 50) {
rate = 0.06;
} else if (purchase < 100 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
} else if (purchase < 500 && [2, 3].includes(dayOfWeek)) {
rate = 0.06;
}
else {
rate = 0.03;
}
let discount = purchase * rate;
let output = purchase - discount;
//Checks if output is a number.
if(isNaN(output)){
output = 'Not a number!';
} else{
output = '$' + output;
}
//Puts the output inside of your "output" <div>
outputEl.textContent = output;
}
</script>
</body>
</html>

how to convert 6 foot 4 inches to meters in javascript

This is my code, I have to convert 6 foot 4 inches to meter and am getting the incorrect number. Can someone help?
var INCHES_TO_CM = 2.54;
var CM_TO_METERS = 0.01;
var FEET_TO_INCHES = 12;
function start(){
convertHeightToMeters(6,4);
}
function convertHeightToMeters(feet, inches){
var meters = FEET_TO_INCHES + INCHES_TO_CM * CM_TO_METERS;
println(meters);
}
function convertHeightToMeters(feet, inches) {
return ((feet * FEET_TO_INCHES) + inches) * INCHES_TO_CM * CM_TO_METERS;
}
This is a simple way for beginners.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 id"p1">The conversion</h1>
<script src="myjsfilename.js"></script>
</body>
</html>
The javascript
var conversion = function(foot, inch) {
var inch = inch*2.54;
var foot = foot*30.48;
var result = inch + foot;
result = result/100 + 'm;'
document.getElementById("p1").innerHTML = result;
};
conversion(6, 4);
And an example of how you can turn this into a very simple website (https://conversionfttom.000webhostapp.com/)

Why I Can't Get A Return Value To BAC?

<!DOCTYPE html>
<html>
<meta content="text/html; charset=utf-8">
<head>
<title>BAC Calculator</title>
//form for my html page. Not sure weather to use submit or just a button for this type. also if the return form is what is correct or not.
<form action="" onSubmit="return formbac()" id="formbac">
Weight:<input id="weight" name="weight1" type="number">
Beer:<input id="beer" name="beer1" type="number">
Wine:<input id="wine" name="wine1" type="number">
Shots:<input id="shots" name="shots1" type="number">
Time:<input id="time" name="time1" type="number">
<input name="submit" type="submit" value="Calculate">
<hr>
BAC: <input type="" name="bac" id="BAC">
</form>
</head>
<body>
//Javascript code for calculations
I think this is correct but i could possibly be mixing code up with my calculations//
<script>
// Basic function
function formbac(){
//values
var weight = document.getElementById("weight").value;
var beer = document.getElementById("beer" * .54).value;
var wine = document.getElementById("wine" * .6).value;
var shots = document.getElementById("shots" * .6).value;
var time= document.getElementById("time").value;
var BAC = 0;
//trying to get my output of baclevels
// calculations
var BAC = ((beer + wine + shots * 7.5) / (weight * .68)) - (0.015 * time);
//decimal round
var BAC = math.round(bac*100)/100;
//output
var BAC = document.getElementById(BAC).value;
}
</script>
</body>
</html>
Your output should be the other way around:
//output
document.getElementById('BAC').value = BAC;
Also, all the multiplications you're trying to perform inside document.getElementById should go outside. For example:
var beer = document.getElementById("beer").value * .54;
Try this line instead
document.getElementById("BAC").value = BAC; //notice "BAC" instead of BAC, you're trying to grab the element that doesn't exist
// calculations
var BAC = ((beer + wine + shots * 7.5) / (weight * .68)) - (0.015 * time);
//decimal round
var BAC = math.round(bac*100)/100; //override above value
//output
var BAC = document.getElementById(BAC).value; //override above value
As per your code your output will be the value of input control.

Categories

Resources