Javascript: Having issues calling function(Cannot read property 'value' of null) - javascript

So i've been trying to debug this for a few hours and I'm completely stuck. When I go on the webpage I get this error in the console:
(Cannot read property 'value' of null at totalCost (assn1.html:18) at assn1.html:26 totalCost # assn1.html:18
(anonymous) # assn1.html:26.
My program is all finished I just can't get it to call the function and print the name, number of cups and the total cost at the end.
Heres my code:
<html>
<head>
<title>Tea Shoppe</title>
</head>
<body>
<section>
<h1> Welcome to the Tea Shoppe!</h1>
<p>
<img src = "http://nobacks.com/wp-content/uploads/2014/11/Tea-Cup-5-500x476.png" />
</p>
</section>
<script>
function totalCost()
{
var cups = parseInt(document.getElementById("cups").value);
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
totalCost(cups);
document.write("Ok" + name + ", you ordered" + cups + " of tea" + "your total price is" + totalCost);
</script>
</body>
</html>

document.getElementById("cups")
You have no element with that ID in your document.

function totalCost(cups)
{
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
document.write("Ok " + name + ", you ordered" + cups + " of tea" + " your total price is " + totalCost(cups));
Here's a working version of your code, what i did here is adding teh totalcost function parameter since you pass it when you call the function and got rid of the cups variable inside your function because it has nothing to do there and was causing an error also + and changed the place where you function should be called from since it returns the totalcups value it must be put inside the document.write function to return the total in it's perfect place.
that's all and i hope this fixed your problem.
herre's a working fiddle https://jsfiddle.net/bgn4x7ej/

Related

JS function formating currency

Good morning folks. I just started to learn JS and got a task in which I am stuck. I need to change number format to have 2 decimal places and it should also start with pound sign.
function formatCurrency() {
var formated = formated.toFixed(2);
return formated;
}
function calculateSalesTax(price: number) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
When I tried to shorten numbers it throws me an error.Could you please point me in correct direction, as it looks like a very simple task.
Try like this:
function formatCurrency(price) {
var formated = price.toFixed(2);
return formated;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
The formatCurrency function needs to accept an argument (the price) passed into it and use that in the formatting.
The calculateSalesTax function shouldn't have the type definition added to the argument (this is fine in TypeScript).
Here is your correct code:
function formatCurrency(price) {
return `\u00A3 ${price.toFixed(2)}`;
}
function calculateSalesTax(price) {
return price * 0.21;
}
const product = "You don't know JS";
const price = 19.99;
const salesTax = calculateSalesTax(price);
console.log("Product: " + product);
console.log("Price: " + formatCurrency(price));
console.log("Sales tax: " + formatCurrency(salesTax));
console.log("Total: " + formatCurrency(price + salesTax));
You were not declaring an argument for formatCurrency. \u00A3 is the code for the pound sign, as putting £ will result in a bad behaviour in js. The backticks (``) allows you to use "literal", go search for it, it is a useful tool in javascript. Also, you attempted to declare a return type for calculateSalexTaxPrice, which you can not since typing is possibile in TypeScript only

Declaration or statement expected in else statement

I'm fairly new to java script and I've encountered a problem while trying to make a else statement in visual studio 2017.
I've tried moving the curly brackets and the else around to see if maybe I've placed them into the wrong place and I've had no luck.
<script type="text/javascript">
var items = parseInt(prompt("enter number of items", ""));
var price = parseFloat(prompt("enter item price", ""));
var total = items * price
if (total >= 50); {
document.write("<h3>" + "cost... $" + total * .5 + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
else {
document.write("<h3>" + "cost... $" + total + "</h3>");
document.write("<h2>" + prompt("enter a name", "") + "</h2>");
}
</script>
Whenever I open it in a web page, nothing happens, But when i get rid of the else statement, the if statement would execute.
Delete the semicolon behind the if condition and then the code should work.

Making a one rep max calculator in JavaScript, not sure why my function isn't working

I am making a one rep max calculator using the Epley Formula. When I call the function, it says it's undefined. However, I thought by using the parameters weight and reps, which have also been parsed as integers, that they would be sufficient to implement the function.
Here is my fiddle.
What am I doing wrong?
HTML:
<div>
<h2>Calculator for Epley Formula One Rep Max</h2>
<p>Use the spaces below to type in the weight and reps for any lift to calculate any estimated 1-Rep Max using the Epley Formula:</p>
<b>Weight</b>
<input type="text" id="weight">
<b>Reps</b>
<input type="text" id="reps">
<button id="button">Click Me</button>
<br></br>
<hr>
<div id="demo">Go for it!</div>
</div>
JavaScript:
$("#button").click(function(){
var weight = parseInt($('#weight').val());
var reps = parseInt($('#reps').val());
$('#demo').html("");
function calculateMax (weight, reps) {
weight * (1 + (reps/30))
};
$('#demo').html("If you can lift " + weight + " for " + reps + " reps then you have an estimated max of " + calculateMax(weight, reps) + " !");
});
You want to return the calculated value from the calculateMax function
function calculateMax(weight, reps) {
return weight * (1 + (reps/30));
}
This said, I can't see why you are using a separate function for that, why not write it like this:
$("#button").click(function(){
var weight = parseInt($('#weight').val());
var reps = parseInt($('#reps').val());
var max = weight * (1 + (reps/30));
$('#demo').html("If you can lift " + weight + " for " + reps + " reps then you have an estimated max of " + max + " !");
});
You need to use return:
function calculateMax (weight, reps) {
return weight * (1 + (reps/30))
};

Code won't run because I can't output more than one variable in document.write

My code won't run when I try to display more than one variable in the document.write section of the code. I'm pretty sure I was doing everything right.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " +name )
document.write("<p>The cost of buying " +quantity "of " +product "is " +costoforder </p>)
document.write("<p>The discount for this purchase is " +discounted </p>)
document.write("<p>With discount, your total order cost is " +totalorder</p>)
</script>
You are missing some plus signs in your string concatenation.
"<p>The cost of buying " + quantity + " of " + product + " is " + etc.
You are missing "+" signs after your variables.
You put
"String" + variable "string"
Instead of
"string" + variable + "string"
Several times in your document.write statements
You need to use the plus sign, +, for string concatenation. Also you are missing the ; after the statements.
<script type="text/javascript">
var name = prompt("Welcome to the Fruity Store. What is your name?","");
var product = prompt("What is the name of the product you would like?","");
var price = 1*prompt("How much does it cost?","");
var quantity = 1*prompt("How many of the fruit would you like?","");
var discount = 1*prompt("What was the discount of the product in decimal form?","");
var costoforder = (price*quantity);
var discounted = (price*quantity*discount);
var totalorder = (costoforder - discounted);
document.write("Thank you for placing an order with us " + name );
document.write("<p>The cost of buying " + quantity + "of " + product + "is " + costoforder + "</p>");
document.write("<p>The discount for this purchase is " + discounted + "</p>");
document.write("<p>With discount, your total order cost is " +totalorder + "</p>");
</script>

Error when calling JavaScript function — "can't find variable"

I'm attempting to complete and exercise from the JavaScript Bible, and am having trouble getting my script to function.
The assignment is to create a page that allows users to query a planet's name, and, via a script that matches the planet's name with its data stored in the associate arrays, call up its distance and diameter information.
I'm attempting to call the function 'getPlanetInfo' via a button (onclick='getPlanetInfo()'). However, my error console reports that it cannot find a variable named 'getPlanetInfo' when I attempt to run it.
I've attached both my JS and HTML code below. Any idea as to why my function isn't being properly called would be hugely appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="planets.js"></script>
</head>
<body>
<h1>Check a planet's distance from the sun and its diameter!</h1>
<form>
<input type="text" name="entry" id="entry">
<input type="button" value="Check it!" onClick="getPlanetInfo()">
</form>
</body>
</html>
JS:
var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";
var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";
var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";
function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
if (planetNames[i] == selectedPlanet)
{
break;
}
}
if (i < planetNames.length)
{
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}
else
{
alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}
This line:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
is missing a + sign after planetDistances[i], so the function has a syntax error and is not created, and naturally it's not found when called.
http://www.jsfiddle.net helps you create a reproducible case that we can all see, use it when you need to ask js questions.
You're missing a + - this:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
should be
alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
You should use something like Firebug to catch syntax errors when loading your script.

Categories