<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Cost Calculator</title>
</head>
<body>
<h1>
College Cost Calculator
</h1>
<form>
<input type= "numbers" id= "annualCost" placholder= "annual cost" />
<br>
<input type= "numbers" id= "inflationRate" placholder= "inflationRate" />
<br>
<input type= "numbers" id= "yearsUntilCollege" placholder= "yearsUntilCollege" />
<input id= "button" type="button" value = "Estimate" onclick= "calculator()"/>
<input id= "reset" type="reset" value = "Reset"/>
</form>
<p id= "result">
</p>
<script>
// your code here
document.getElementById(button) = function calculator () {
let inflationRate = document.getElementById(inflationRate);
let annualCost = document.getElementById(annualCost);
let totalCost;
let annualSaving;
let yearsUntilCollege = document.getElementById(yearsUntilCollege);
totalCost = annualCost;
let amount = (inflationRate * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 2) * annualCost) + annualCost;
totalCost += amount;
amount = ((inflationRate * 3) * annualCost) + annualCost;
totalCost += amount;
annualSaving = totalCost / 5;
return amount
return annualSaving
console.log(`For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`);
console.log(`You have to pay $${totalCost}.`);
console.log(`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`)
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
}
</script>
</body>
</html>
This is a code to calculate the college cost for Four(04) years including inflation and how much to save before college begins.
Help me figure out the issue with this code. It keeps giving syntax Error 28:15 and reference Error. I can't seem to figure out what I have done wrong and did I call the function correctly?
Many issues here:
1- Element IDs are strings. Therefore, document.getElementById expects you to pass a string to it, and strings are surrounded by quotation marks (' or ").
2- To get the value of <input> elements, you should use .value. So for example:
//get the value of input with id "inflationRate"
var inflationRate = document.getElementById("inflationRate").value;
3- To call a function on button click, use the button's onclick event, like so:
function calculator() {
//do something...
}
//call the function calculator whenever the button is clicked
document.getElementById("button").onclick = calculator;
4- As pointed out by #ecg8 in the comments, return statements jump out of the function immediately, and therefore you cannot have further statements/computations after the return statement, as they will not be reached.
And as a side note, in your HTML, numeric inputs should have a type of number and not numbers.
Edit: Also, in your last statement here:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
`You have to pay $${totalCost}.`
`You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`
To concatenate these three strings into one, either wrap the entire string (all the lines) into one pair of backticks (`), or use the + operator to concatenate the strings:
document.getElementById(result).innerHTMl = `For a 4 years college degree with Annual cost: $${annualCost} and Inflation rate: ${inflationRate}`
+ `You have to pay $${totalCost}.`
+ `You need to save ${annualSaving} annually for ${yearsUntilCollege} years.`;
On a final note, all these issues are basic Javascript stuff, so I
would really recommend to study and understand the basics of
Javascript (syntax, functions, events, etc.) before solving problems
like this one.
Related
I have been given this logic table that I need to use if else statement to get a promotion price based on user input.
How to declare that logic table in javascript? So that I can print out the correct output based on the table.
For example; if user input is 5, so, I need an expected output of (price 3 + price 2).
function checkQuantity() {
let userInput = document.getElementById('quantity').value;
userInput = Number(userInput); //Convert string to number data type
var pizzaPrice = 6.45;
var pizzaPrice2 = 12.00;
var pizzaPrice3 = 14.00;
if (!userInput) {
console.log("Please enter a valid pizza quantity");
} else if (isNaN(userInput)) {
console.log("Error!!");
} else if (userInput < 1) {
console.log("Minimum pizza order is 1.");
} else {
document.getElementById('message').innerHTML = 'Number of pizza : ' + //Price hasn't been declared yet;
}
return false;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ordering form</title>
<script src="linked.js"></script>
</head>
<body>
<h1>PizzasOnly ordering form</h1>
<p>Simply enter the number of pizzas you want into the input below to find out the cost of your order</p>
<form action="#" method="post" id="orderForm" onsubmit="return checkQuantity()">
<p>
<label for="quantity">Enter number of pizzas wanted:</label>
<input name="quantity" id="quantity" value="">
</p>
<p>
<input value="Total cost" type="submit">
</p>
</form>
<div id="message"></div>
</body>
</html>
The formula can be assembled as a one-liner:
~~(i/3)*price + xtra[i%3]
~~ (the repeated application of the "bitwise NOT operator") is a shorthand notation for Math(floor(), % is the modulo operator that will return the remainder of a division, the rest should be clear.
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i)) )
In this later version I defined the function price(). It can be called with one argument (i: number of pizzas) as you can see above.
The optional arguments p3 (price for a bundle of 3) and xtr (addon for zero, one or two extra pizzas) can be supplied if you want to use a different pricing structure than the default one, see here:
const price=(i,p3=14,xtr=[0,6.45,12])=>~~(i/3)*p3 + xtr[i%3];
[...Array(14)].map((_,i)=>i+1).concat([50,100,1500,1276]).forEach(i=>console.log(i,price(i,16,[0,6,11])) )
I am trying to write a simple one page calculator script with user input. With my semi-lack of JS knowledge I keep running into issues. I feel like what I am doing should work and is correct but I am obviously missing something here.
I would like my HTML input box's to set the variables for my JS function. I just can not figure out what I am doing wrong here.
If I could have a nudge in the right direction I would be more than thankful.
<body>
<input type="text" id="price"=>Price</input>
<br>
<input type="text" id="value"=>Value</input>
<br>
<button onclick="sub()">Submit</button>
</body>
<script>
function sub() {
var value = document.getElementById("value").value;
var price = document.getElementById("price").value;
var keep = value * 0.7
var sell = keep * 0.7
var profit = sell / 1000 * 6 - price
var keeprate = price / keep * 1000
var earned = profit + price
document.write("Keeping: R$ ");
document.write(keep);
document.write("<br>");
document.write("1k Buy Rate: $");
document.write(keeprate);
document.write("<br>");
document.write("<br>");
document.write("Selling: R$ ");
document.write(sell);
document.write("<br>");
document.write("1k Buy Rate: ");
document.write("$6.00");
document.write("<br>");
document.write("<br>");
document.write("Total Cost $");
document.write(price)
document.write("<br>");
document.write("Total Return $");
document.write(earned)
document.write("<br>");
document.write("Net: $");
document.write(profit);
}
</script>
I think your main issue is your function declaration. You have no opening and closing bracket for function sub()
Add an opening and closing bracket to properly declare your function.
function sub() {
code
}
A parking garage charges a $2.00 minimum fee to park for up to three hours. It charges an additional $0.50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time.
The web page should calculate the entry hour and minute as well as the exit hour and minute with text boxes. Hours will be entered in a 24 hour format. Once the submit button is selected, the webpage should display the charge, total number of charges and running total of charges. Note that the latter two values will be maintained as the page is used repetedly.
Create and use functions calculateTime and calculateCharge, the former to figure the amount of time in the garage and the latter to figure the charge.
I got the HTML running, however I cannot get the values to display on to the textbox. I also cannot figure out how to calculate the charge. Any help would be appreciated! Thank you.
HTML CODE:
<!DOCTYPE html>
<html>
<head>
<title>Parking Charge</title>
</head>
<body><div align="center">
<form id="1"><h1><p style="background-color:black ; color:gold;">Parking Garage Charge Calculator</p></h1><hr>
<p>ENTRY TIME: <input type = "number" name = "EntryTime" id = "entTime"></p>
<p>EXIT TIME : <input type="number" id="extTime" name="ExitTime">
<p>Number of Hours Parked: <input type ="number" name="noOfHours" id="nh"><br><br>
<input type="button" id="calculate" name="calc" value="Calculate" onclick="calculateTime()"/>
<input type="reset" id="resetBtn" value="Clear"><br><br>
<input type="number" id="total" name="totalCost" placeholder="Your Total Payment" readonly/><hr>
</form>
</div>
</body>
<script src="P2JS.js"></script>
</html>
JAVASCRIPT CODE:
function calculateTime(){
var EntryTime = document.getElementById('entTime').value;
var ExitTime = document.getElementById('extTime').value;
var noOfHours = (EntryTime - ExitTime);
document.getElementById("nh").innerHTML = noOfHours;
}
/*Function to calculate the payment on the number of hours parked*/
function calculateCharge(){
var charge = 3.50;
var payment = (noOfHours * charge);
if (noOfHours <= 3){
totalPayment = charge * noOfHours;
return payment;
}
else {
payment = ((noOfHours - 3) * (charge + 0.50)) + (charge * 3);
return payment;
}
}
The reason the hours aren't showing is because your are using an input to display it and asking it to show it in the innerHTML which input doesn't have.
So what you want is give it a value instead.
Just add ' value="" ' to your input html
<input type="number" name="noOfHours" value="" id="nh">
and change '.innerHTML' for '.value' in your js.
document.getElementById("nh").value = noOfHours;
You might also want to change your equation for ExitTime - EntryTime because right now it gives you a negative number of hours ;)
<!doctype html>
<html>
<head>
<title> Daily Recommended Exercise </title>
</head>
<body>
<h2>Your Daily Exercise Schedule</h2>
<p>Please select your age group:</p>
<form>
0 - 5: <input type = "radio" name = "PickAge" value = "Age1">
<br/>
6 - 17: <input type = "radio" name = "PickAge" value = "Age2">
<br/>
18 - 64: <input type = "radio" name = "PickAge" value = "Age3">
<br/>
65 - 150: <input type = "radio" name = "PickAge" value = "Age4">
<br/>
<input type="button" onclick = "exerciseRecommend();" value = "Enter"></input>
</form>
<script type = "text/javascript">
function exerciseRecommend()
{
var age = document.getElementsByName("PickAge");
if (age=="Age1")
{
alert("Physical activity in infants and young children is necessary for healthy growth and development. There are no guidelines for children at this age though regular physical activity is recommended.");
}
else if (age=="Age2")
{
alert("At this age you should do 60 minutes or more of physical activity each day. This includes, aerobic endurance and strength exercises.");
}
else if (age=="Age3")
{
alert("At this age you should be doing two hours and thirty minutes or more of moderate aerobic endurance and strength exercises activity every week OR one hour fifteen minutes of intense aerobic endurance and strength exercises activity OR a mix of the two.");
}
else if (age=="Age4")
{
alert("At this age you should be exercising 2-3 hours a week. It is recommended that you should be doing mild endurance and strength activities.");
}
}
</script>
</body>
</html>
What is wrong with this code? Whenever I press the button nothing happens!! I have tried again and again but for some reason it is not finding the user input and outputting any alert values! Please help!
Shashank is correct that best practice is to attach the event listener through JS itself, but in your case I'll assume that you're learning the language and just want to know what's up and how it works.
So, let's take a look at your age variable. If you console.log(age) after you define it, it will return a Node list of all of the elements with the name "PickAge". What you want is a specific one of those, the checked one.
// Get a list of all the select-able ages
var allAges = document.getElementsByName("PickAge");
// Define a variable that will hold our selected age
var age;
// Iterate through all of the select-able ages
for (i = 0; i < allAges.length; i++) {
// If the selected age is checked, set it to the "age" variable
if (allAges[i].checked === true) {
// We grab only the value here because that's what you check later
age = allAges[i].value;
}
}
That should give you the correct result that will work with your if < alert. You might want to add an else statement at the end in case the user doesn't select any age, though.
Just to make sure you know, this isn't best practice, efficient, or the best way of doing this. This is just a quick example to help you understand the process a bit to help you get the basis for the language.
I am very new to Javascript, only a few weeks, and am stuck on something I assume to be simple. I have searched for hours, but cant find an example to point me in the right direction. Im basically wanting to create a simple "Running Balance" calculator. One textbox has the input (added by using add button) and the other textbox has the output. The output should change depending on what I put into the input textbox and keep adding to the value in the output textbox.
Here is my code in Javascript:
var accountBalance = 0;
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
total = parseInt(inPrice += accountBalance);
document.getElementById("outBalance").value = total;
}
and the HTML:
<form id="form2" name="form2" method="post" action="">
<p>
Enter an amount:
<input type="text" name="inAmt" id="inAmt" />
</p>
<p>
Display Balance::
<input type="text" name="outBalance" id="outBalance" />
</p>
</form>
<p><input type="button" id="addBal" value="Add the amount to the balance" onclick="addBalance()"/></p>
I have a feeling my total variable in my function is what I am screwing up. Thanks in advance for the help!!
This part doesn’t really make sense:
total = parseInt(inPrice += accountBalance);
It takes accountBalance (0), appends it to inPrice (since inPrice is a string), stores the value back in inPrice, parses the result as an integer, and sets total to that integer. What you seem to need is pretty much the reverse, that is:
Parse inPrice so that it’s a number instead of a string
Add it to accountBalance and store the result in accountBalance
Put the new accountBalance in total (or just use accountBalance in the first place)
Or, in JavaScript:
var accountBalance = 0;
function addBalance() {
var inPrice = parseInt(document.getElementById("inAmt").value, 10);
accountBalance += inPrice;
document.getElementById("outBalance").value = accountBalance;
}
You've confused a few variables - the problem was you were never reading the current balance and you were resetting the total variable every time (aside from mixing ints and strings). Here is a version without the total variable:
function addBalance()
{
var inPrice = document.getElementById("inAmt").value
accountBalance += parseInt(inPrice, 10);
document.getElementById("outBalance").value = accountBalance;
}
See it here: http://jsfiddle.net/fdureo1s/