Program returning values as NaN - javascript

Im trying to get this program to work and i have everything running, but my values return as NaN. I've tried initializing the variables as numbers both in and outside the function to no avail. Any help?
EDIT: added in the entire script, html and all incase it helps alongside the edits suggested thus far.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>Placeholder</title>
</head>
<body>
<header>
<h1>Resturant Calculator</h1>
</header>
<article>
<fieldset>
<label for="bill">
Bill Amount
</label>
<input type="number" id="bill" />
</fieldset>
<fieldset>
<label for="tip">
Tip Percent
</label>
<input type="number" id="tip" />
<label>(enter as whole number)</label>
</fieldset>
<fieldset>
<label for="peeps">
# of people
</label>
<input type="number" id="peeps" />
</fieldset>
<button id="submit" onclcick="calculate()">Calculate</button>
<p id="tipAmount">Tip Amount:</p>
<p id="total">Total Bill:</p>
<p id="totalByPeep">Total per Person:</p>
</article>
<script>
"use strict"
var bill = document.getElementById("bill").value;
var tip = document.getElementById("tip").value;
var peeps = document.getElementById("peeps").value;
var total;
var totalTip;
var tpPerson;
function calculate(){
totalTip = bill.value / (tip.value * 0.01);
total = bill.value + totalTip;
tpPerson = total / peeps.value;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + tpPerson;
}
function createEventListener(){
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener){
submitButton.addEventListener("click", calculate, false);
}
else if(submitButton.attachEvent){
submitButton.attachEvent("onclick", calculate);
}
}
if (window.addEventListener){
window.addEventListener("load", createEventListener, false);
}
else if (window.attachEvent){
window.attachEvent("onload", createEventListener);
}
</script>
</script>
</body>
</html>

You need to get the values from the elements bill,tip,peeps
Probably something like document.getElementById("bill").value
Using just document.getElementById("bill") you are selecting the element, but not its value

You need to read the value inside calculate()
function calculate(){
bill = +bill.value, tip = +tip.value, peeps = +peeps.value;
totalTip = bill/ (tip * 0.01);
total = bill + totalTip;
tpPerson = total / peeps;
document.getElementById("tipAmount").innerHTML = "Tip Amount: " + totalTip;
document.getElementById("total").innerHTML = "Total: " + total;
document.getElementById("totalByPeep").innerHTML = "Total per Person: " + +tpPerson;
}

Related

Empty input fields/values after form submit

I've got a very simple form and I'm want the values to empty when I submit in order to use again without refreshing the page. What I've got isn't working for some reason.
My initial idea was to set the values of the inputs to empty strings on form submit, but when I log them into the console they don't do that. Anyone know what I'm doing wrong here?
<!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>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
let form = document.getElementById("form");
let volume = document.getElementById("volume");
let denied = document.getElementById("denied");
let charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function (e) {
e.preventDefault();
volume = volume.value;
denied = denied.value;
charges = charges.value;
let curDenialRate = parseFloat((denied / volume) * 100);
charges = parseFloat(charges * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(charges);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
volume = " ";
denied = " ";
charges = " ";
return false;
};
Use HTMLFormElement.reset():
let form = document.getElementById("form");
const volume = document.getElementById("volume");
const denied = document.getElementById("denied");
const charges = document.getElementById("charges");
let submit = document.getElementById("btn-submit");
let results = document.querySelector(".results");
let rate = document.querySelector(".rate");
let recoverable = document.querySelector(".recoverable");
form.onsubmit = function(e) {
e.preventDefault();
let a = volume.value;
let b = denied.value;
let c = charges.value;
let curDenialRate = parseFloat((b / a) * 100);
c = parseFloat(c * 0.4);
function formatNumber(num) {
let formattedNum = num.toFixed(2);
return formattedNum;
}
let recoverableDollars = "$" + formatNumber(c);
curDenialRate = formatNumber(curDenialRate) + "%";
rate.append(curDenialRate);
recoverable.append(recoverableDollars);
form.reset();
return false;
};
<!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>
<form id="form">
<input id="volume" type="text" />
<input id="denied" type="text" />
<input id="charges" type="number" step="any" />
<button id="submit" type="btn-submit">Submit</button>
</form>
<div class="results">
<p class="rate">Current Denial Rate: </p>
<p class="recoverable">Recoverable Dollars: </p>
</div>
<script src="script.js"></script>
</body>
</html>
How you are clearing values will not work. You are trying to change the variable but that will not affect the DOM element or its value.
You will have to use the below code with value property to change the value.
document.getElementById("volume").value= " ";
document.getElementById("denied").value= " ";
document.getElementById("charges").value= " ";

How to get a span element to show a value?

I have an HTML file with a .js file that has the javascript.
In the HTML file I have <p>Total Estimate: <span id= "estimate"></span></p>
But nothing shows up when opened in a browser. This is a practice that you are supposed to go along with in my textbook and as far as I can see, I am doing it correctly. I am getting an error in the JS that says
ERROR:'document' is not defined.[no-undef]
This is where ever document is seen in the JS.
This is my JS code. Is there a problem I don't see?
// global variables
var photographerCost = 0;
var totalCost = 0;
var memoryBook = false;
var reproductionRights = false;
// calculates all costs based on staff and adds to total cost
function calcStaff() {
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs");
var distance = document.getElementById("distance");
totalCost -= photographerCost;
photographerCost = num.value * 100 * hrs.value + distance.value * num.value;
totalCost += photographerCost;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// adds/subtracts cost of memory book from total cost
function toggleMembook() {
(document.getElementById("membook") .checked === false) ?
totalCost -= 250 : totalCost + 250;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// ads/subtracts cost of reproduction rights from total cost
function toggleRights() {
(document.getElementById('reprodrights') .checked === false) ?
totalCost -= 1250 : totalCost += 1250;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}
// sets all form field values to defaults
function resetForm() {
document.getElementById ("photognum") .value = 1;
document.getElementById ("photoghrs") .value =2;
document.getElementById ("membook") .checked = memoryBook;
document.getElementById ("reprodrights") .checked = reproductionRights;
document.getElementById ("distance") .value = 0;
calcStaff();
createEventListeners();
}
// creates event listeners
function createEventListeners() {
document.getElementById("photognum") .addEventListener("change", calcStaff, false);
document.getElementById("photoghrs") .addEventListener("change", calcStaff, false);
document.getElementById("membook") .addEventListener("change", toggleMembook, false);
document.getElementById("reprodrights") .addEventListener("change", toggleRights, false);
document.getElementById("distance") .addEventListener("change", calcStaff, false);
}
// resets form when page is reloaded
document.addEventListener("load", resetForm, false);
Below is HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Fan Trick Fine Art Photography - Estimate</title>
<link rel="stylesheet" media="screen and (max-device-width: 999px)" href="fthand.css" />
<link rel="stylesheet" media="screen and (min-device-width: 1000px)" href="fantrick.css" />
<!--[if lt IE 9]>
<link rel="stylesheet" href="ftie.css" />
<![endif]-->
<link href='http://fonts.googleapis.com/css?family=Mr+Bedfort' rel='stylesheet' type='text/css'>
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<div id="container">
<header>
<h1>
<img src="images/ftlogo.png" alt="Fan Trick Fine Art Photography" title="" />
</h1>
</header>
<nav>
<ul>
<li>About</li>
<li>Portfolio</li>
<li id="currentpage">estimate</li>
<li>Digital 101</li>
</ul>
</nav>
<article>
<h2>Estimate</h2>
<p>Our experienced, professional photography team is available to capture memories of your wedding, celebration, or other special event.</p>
<p>Choose the custom options that fit your needs:</p>
<form id="estimateform">
<fieldset>
<legend><span>Photography</span></legend>
<input type="number" min="0" max="4" id="photognum" value="1" />
<label for="photognum">
<p># of photographers (1‑4)</p>
<p>$100/hr</p>
</label>
<input type="number" min="2" id="photoghrs" value="2" />
<label for="photoghrs">
<p># of hours to photograph (minimum 2)</p>
</label>
<input type="checkbox" id="membook" />
<label for="membook">
<p>Memory book</p>
<p>$250</p>
</label>
<input type="checkbox" id="reprodrights" />
<label for="reprodrights">
<p>Reproduction rights for all photos</p>
<p>$1250</p>
</label>
</fieldset>
<fieldset>
<legend><span>Travel</span></legend>
<input type="number" id="distance" value="0" />
<label for="distance">
<p>Event distance from Austin, TX</p>
<p>$1/mi per photographer</p>
</label>
</fieldset>
</form>
</article>
<aside>
<p>Total Estimate: <span id= "estimate"></span></p>
</aside>
<footer>
<p>Fan Trick Fine Art Photography • Austin, Texas</p>
</footer>
</div>
<script src="ft.js"></script>
</body>
</html>
You can try this code below
function calcStaff() {
var num = document.getElementById("photognum");
var hrs = document.getElementById("photoghrs");
var distance = document.getElementById("distance");
totalCost -= photographerCost;
//You need use Number to change all value
//fix
photographerCost = Number(num.value) * 100 * Number(hrs.value) + Number(distance.value) * Number(num.value);
//============//
//This code systax not support
//photographerCost = num.value * 100 * hrs.value + distance.value * num.value;
totalCost += photographerCost;
document.getElementById("estimate") .innerHTML = "$" + totalCost;
}

When I click the Calculate button, it does not display the calculations in textbox for sales tax and total

When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>

JavaScript Error Finding the error on why my qty of items *cost of items won't give me a final answer

Can Someone help me? so my code allows me to send out an alert box when I run my system; first name, last name, street address, city, state, zip, something you want to buy and some type of amount. It runs but then it doesn't display the final amount of the (qty* cost of the item) at the end.
Am I missing something? how can I get it working?
Once I have the website I have no error, when I run it and it reaches the end I receive an error (Uncaught TypeError: Cannot set property 'value' of null) this line
if (document.getElementById("txtPurchase").value= "Gameboy"){
and <p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()" ></p>
(Uncaught TypeError: Cannot set property 'value' of null
at ordering (line:35)
at HTMLInputElement.onclick (line:85)
ordering (line:35)
onclick (line:85)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value = "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementsById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value = "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value = "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
Use == instead of = in if conditions
And
In one place you use getElementsById("quantity")
Instead use getElementById("quantity") //No 's'
So your script tag should look like
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
alert(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
alert(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
alert(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
alert(city);
var state;
state = document.practiceForm.txtState.value;
alert(state);
var zip;
zip = document.practiceForm.txtZip.value;
alert(zip);
if (document.getElementById("txtPurchase").value == "Gameboy") {
var gameboyPrice = 25;
var gameboyQuantity = document.getElementById("quantity").value;
var gameboyTotal = gameboyPrice * gameboyQuantity;
alert("total: $" + gameboyTotal);
} else if (document.getElementById("txtPurchase").value == "DSI") {
var dsiPrice = 50;
var dsiQuantity = document.getElementsById("quantity").value;
var dsiTotal = dsiPrice * dsiQuantity;
alert("total: $" + dsiTotal);
} else if (document.getElementById("txtPurchase").value == "WII") {
var wiiPrice = 75;
var wiiQuantity = document.getElementsById("quantity").value;
var wiiTotal = wiiPrice * wiiQuantity;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()"></p>
</form>
</body>
</html>
var dsiQuantity=document.getElementsById("quantity").value;
you have a typo mistake here. Change it to
var dsiQuantity=document.getElementById("quantity").value;
Two things you need to change
1. in if condition - put == in place of =
2. for numeric value you need to parse them into proper number (i.e. int or float)
<!DOCTYPE>
<html lang="en">
<head>
<meta charset="utf-8" />
<title> Confirmations on orders</title>
</head>
<body>
<script type="text/javascript">
function ordering() {
var firstName;
firstName = document.practiceForm.txtFirstName.value;
console.log(firstName);
var lastName;
lastName = document.practiceForm.txtLastName.value;
console.log(lastName);
var streetAddress;
streetAddress = document.practiceForm.txtStreetAddress.value;
console.log(streetAddress);
var city;
city = document.practiceForm.txtCity.value;
console.log(city);
var state;
state = document.practiceForm.txtState.value;
console.log(state);
var zip;
zip = document.practiceForm.txtZip.value;
console.log(zip);
var purchase = document.getElementById("txtPurchase").value;
// parse value in Float type data.
var qty = parseFloat(document.getElementById("quantity").value);
// USE == for comparison
if (purchase == "Gameboy") {
var gameboyPrice = 25;
var gameboyTotal = gameboyPrice * qty;
alert("total: $" + gameboyTotal);
} else if (purchase == "DSI") {
var dsiPrice = 50;
var dsiTotal = dsiPrice * qty;
alert("total: $" + dsiTotal);
} else if (purchase == "WII") {
var wiiPrice = 75;
var wiiTotal = wiiPrice * qty;
alert("total: $" + wiiTotal);
}
}
</script>
<form name="practiceForm">
<p>First Name: <input type="text" name="txtFirstName"></p>
<p>Last Name: <input type="text" name="txtLastName"></p>
<p>Street Address: <input type="text" name="txtStreetAddress"></p>
<p>City: <input type="text" name="txtCity"></p>
<p>State: <input type="text" name="txtState"></p>
<p>Zip: <input type="text" name="txtZip"></p>
<p>What do you want to purchase today?:
<select id="txtPurchase">
<option value="Gameboy">Gameboy $25 each</option>
<option value="DSI">DSI $50 each</option>
<option value="WII">Wii $75 each</option>
</select>
</p>
<p>How much would you like to buy?: <input type="number" id="quantity"></p>
<p><input type="button" value="Go!" name="btnSubmit" onclick="ordering()">
</p>
</form>
</body>
</html>

Javascript Shipping Calculator Not Grabbing Input

I am getting the headache of a lifetime. I'm not too great with Javascript so I have no idea what's going on. I'm supposed to be coding a text box that when a price is entered and submitted it will calculate the shipping and tell you the total. Everything is working except for the fact that the typed value isn't being set. So the price seems to be permanently set at NaN no matter what is inputted. What am I doing wrong? D:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price + shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5;
} else {
return price * 10 / 100
}
}
/* ]]> */
</script>
</body>
</html>
Here is a sample which may help you
<input id="amount" type="text" name="purchasePrice" placeholder="0.00" />
<input id="submit" type="submit" value="submit" />
var amount = document.getElementById("amount");
var submit = document.getElementById("submit");
function calculateShipping() {
var price = parseFloat(amount.value) || 0;
if (price <= 25) {
alert("Your total is $" + 1.5);
} else {
alert("Your total is $" + (price * 10 / 100));
}
}
submit.addEventListener("click", calculateShipping, false);
on jsfiddle
JavaScript code runs before it knows price... so anything *,+ NaN is... NaN.
You should call calculation of total while submit is clicked, f.ex. this way:
<!DOCTYPE html>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<form method="post" name="number" onsubmit='calculateTotal()'>
<input type="text" name="purchasePrice" placeholder="0.00" />
<input type="submit" value="submit" />
</form>
<script>
/* <![CDATA[ */
function calculateTotal() {
var price = parseFloat(document.getElementsByTagName("input")[0].value);
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
window.alert("Your total is $" + total + ".");
}
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100 }
}
/* ]]> */
</script>
</body>
</html>
You need to attach an event handler that fires when the user enters a value.
<form method="post" name="number" onsubmit='window.alert("Your total is $" + total + ".");'>
<label for="purchasePrice">Price:</label>
<input type="text" name="purchasePrice" id="purchasePrice" placeholder="0.00" />
<br>
<label for="shipping">Shipping:</label>
<input type="text" name="shipping" id="shipping" disabled>
<!-- <input type="submit" value="submit" /> -->
</form>
<script>
var price;
var shipping = parseFloat(calculateShipping(price));
var total = price+shipping;
function calculateShipping(price) {
if (price <= 25) {
return 1.5; }
else {
return price * 10/100;
}
}
var pp = document.getElementById("purchasePrice");
pp.onkeyup = function(e){
price = calculateShipping(this.value);
document.getElementById("shipping").value = price;
};
</script>
This kind of thing really is easier with a library like jQuery. It also handles the differences between browser implementations for attaching event handlers.

Categories