javascript 101: sales tax calculator does not respond to data entry - javascript

I'm guessing the onload function is not properly implemented. Entering numbers or letters do not get the appropriate error or calculation response.
This is my code as of now:
http://jsfiddle.net/907yn57r/
var $ = function (id) {
return document.getElementById(id);
}
var calculateTaxAndTotals = function () {
var taxRate = parseFloat($("taxRate").value); //The tax rate, as a percentage (e.g. 8.5)
var subTotal = parseFloat($("itemPrice").value); //An item price ex $5.95
$("salesTax").value = "";
$("totalItemCost").value = "";
if (isNaN(taxRate) || taxRate <= 0) {
document.taxCalc.taxRate.focus();
document.$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
} else if (isNaN(itemPrice) || itemPrice <= 0) {
document.$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
} else {
var salesTax = subTotal * (taxRate / 100);
var totalItemCost = salesTax + itemPrice;
$("orderTotal").focus();
alert(totalItemCost);
}
}
window.onload = function () {
calculateTaxAndTotals();
}

There are a couple of problems.
First of all, JSFiddle deals with the main html structure itself, so you don't need new body tags and the like.
Secondly, the Javascript here needs to be loaded in the head or the body (on the top left in JSFiddle you can choose different places for it to be loaded).
Finally, there's a few errors in the definition for CalculateTaxAndTotals, it should say
if (isNaN(taxRate) || taxRate <= 0) {
document.taxCalc.taxRate.focus();
$("taxRateMessage").firstChild.nodeValue = "Please enter a valid value.";
} else if (isNaN(subTotal) || itemPrice <= 0) {
$("priceMessage").firstChild.nodeValue = "Please enter a valid value.";
} else {
var salesTax = subTotal * (taxRate / 100);
var totalItemCost = salesTax + itemPrice;
$("orderTotal").focus();
alert(totalItemCost);
}
Really Fixed Fiddle
The final issue was that you were calling isNaN on itemPrice, but the variable itemPrice didn't exist.

Related

Need to use javascript with try,catch and throw exceptions. I want to use it to check a textbox to make sure it is a number not a letter

When I add the test function it doesn't work. But when I take out the test function it works but still displays any none numbers as nan.
HTML code:
<h2>How many male books would you like to order? : <input type="text" id ="maleTotal"/>
<input type="button" onClick="maleBook()" Value = "Total" />
<p> The total is: <br>
<span id = "result"></span></h2>
</form>
Javascript code:
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
}
function test() {
var x;
x = document.getElementById("maleTotal").value;
try {
if(x == "") window.alert "empty";
if(isNaN(x)) window.alert"not a number";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
For one thing, you're missing parenthesis on alerts. It should be like: window.alert("your message");
For another thing, you're missing brackets on if statements {}
Lastly, you need to call the test() function, maybe chain it in at the end of maleBook()
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
test();
}
function test() {
var x = document.getElementById("maleTotal").value;
try {
if(x == "") {
window.alert( "empty");
}
if(isNaN(x)) {
window.alert("not a number");
}
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
Like the other guys said you are missing the parenthesis at the alerts and a bracket at catch.
I made a change at your javascript code calling test function before you calculate total tax and it became like this.
And it is just a detail but I am passing maleTotal value as a parameter to test function.
function maleBook(){
var malePrice = 14.95;
var tax = .06875;
maleTotal = document.getElementById("maleTotal").value;
if(test(maleTotal)){
totalTax = tax * malePrice * maleTotal
document.getElementById("result").innerHTML = maleTotal * malePrice + totalTax;
}else{
//put some message here
}
}
function test(x) {
var err= true;
try {
if(x == ""){
window.alert("empty");
err=false;
}
if(isNaN(x)){
window.alert("not a number");
err=false;
}
return err;
}catch(err) {
message.innerHTML = "Input is " + err;
return false;
}
}
First of all, your test function has errors: You are forgetting parethesis next to alert:
alert("some message here");
Also, you dont seem to be calling test(). You sould make test() return true/false depending is the input is a number, and call it in your main function
also "message.innerHTML" doesnt seem to have a meaning here. Just use alert on that as well.

How to fix undefined variables after program runs

The program will ask for all inputs and print everything but the variables all come up as undefined.
This is for a web application tied to a HTML document. No errors are thrown when it runs.
function driver(){
var plan1Code = "S";
var plan1Cost = 450;
var plan1Hours = 2.5;
var plan1Pics = 75;
var plan2Code = "G";
var plan2Cost = 750;
var plan2Hours = 5;
var plan2Pics = 125;
var plan3Code = "P";
var plan3Cost = 1000;
var plan3Hours = 8;
var plan3Pics = 225;
var retName = getName();
var retPlan = getPlan();
var retHours = getHours();
var retPics = getPics();
var baseCost, totalCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost;
if (retPlan == plan1Code){
baseCost = plan1Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan1Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan1Pics);
}
else if (retPlan == plan2Code){
baseCost = plan2Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan2Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan2Pics);
}
else if (retPlan == plan3Code){
baseCost = plan3Cost;
upchargeTime, upchargeTimeCost = calcTimeUpcharge(retHours, plan3Hours);
upchargePics, upchargePicsCost = calcPicsUpcharge(retPics, plan3Pics);
}
totalCost = calcTotalCost(baseCost, upchargeTimeCost, upchargePicsCost);
print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost);
}
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
}
function calcTimeUpcharge(hours, baseHours){
upchargeTime = hours - baseHours;
var price;
if (upchargeTime>0){
var upchargeTimeUnits = Math.ceil((upchargeTime)/.5);
upchargeTimeCost = upchargeTimeUnits * 50;
}
else {
upchargeTime = 0;
upchargeTimeCost = 0;
}
return upchargeTime, upchargeTimeCost;
}
function calcPicsUpcharge(pics, basePics){
upchargePics = pics - basePics;
if (upchargePics>0){
upchargePicsunits = Math.ceil((upchargePics)/10);
upchargePicsCost = upchargePicsunits*40;
}
else {
upchargePics = 0;
upchargePicsunits = 0;
}
return upchargePics, upchargePicsCost;
}
function calcTotalCost(baseCost, timeCost, picsCost){
return baseCost + timeCost + picsCost;
}
function print(retName, retPlan, baseCost, upchargeTime, upchargeTimeCost, upchargePics, upchargePicsCost, totalCost){
document.write(retName + ", thanks for using Photosarus!" + "\n");
document.write("<br><br>");
document.write("You selected plan " + retPlan + " at a cost of "+ baseCost );
document.write("<br><br>");
document.write(upchargeTime + "additional hours at a cost of "+ upchargeTimeCost);
document.write("<br><br>");
document.write(upchargePics + "additional pictures at a cost of "+ upchargePicsCost);
}
I expect the output to say
Bill, thanks for using Photosarus!
You selected plan S at a cost of $450
0 additional hours at a cost of $0
0 additional pictures at a cost of $0
But instead I get
undefined, thanks for using Photosarus!
You selected plan undefined at a cost of undefined
undefined additional hours at a cost of undefined
undefined additional pictures at a cost of undefined
You need to return the values from the functions:
function getName(){
var text;
var name = prompt("Enter your name");
if (name == null) {
text = "Please enter a valid name";
}
return name;
}
function getPlan(plan){
var plan = prompt("Enter the selected package");
return plan;
}
function getHours(hours){
var hours = prompt("Enter anticipated coverage hours");
return hours;
}
function getPics(pics){
var pics = prompt("Enter anticipated number of pictures");
return pics;
}

Multiplying variables and showing result in a box

I'm having a problem when trying to multiply the totalPallets by the price-per-pallet ($25) and then showing that in the productSubTotal box. With the code as it is right now, the quatity total shows but when I try to get the price result, it doesn't show the operation. Also, if I try changing anythung from the code, the whole thing breaks down. I'll be thankful if anyone could help me. Thanks
// UTILITY FUNCTIONS
function IsNumeric(n) {
return !isNaN(n);
}
function calcTotalPallets() {
var totalPallets = 0;
$(".num-pallets-input").each(function() {
var thisValue = parseInt($(this).val());
if ( (IsNumeric(thisValue)) && (thisValue != '') ) {
totalPallets += parseInt(thisValue);
};
});
$("#quantitytotal").val(totalPallets);
}
function calcProdSubTotal() {
var prodSubTotal = 0;
$(".totalprice").each(function() {
var valString = parseInt(totalPallets) * multiplier;
prodSubTotal += parseInt(valString);
});
$("#product-subtotal").val(CommaFormatted(prodSubTotal));
};
// "The Math" is performed pretty much whenever anything happens in the quanity inputs
$('.num-pallets-input').bind("focus blur change keyup", function(){
// Caching the selector for efficiency
var $el = $(this);
// Grab the new quantity the user entered
var numPallets = CleanNumber($el.val());
var totalPallets = CleanNumber($el.val());
var prodSubTotal = CleanNumber($el.val());
// Find the pricing
var multiplier = $el
.parent().parent()
.find("td.price-per-pallet span")
.text();
};
// Calcuate the overal totals
calcProdSubTotal();
calcTotalPallets();
});
function CommaFormatted(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = "$" + minus + n;
return amount;
}
});

Javascript Functions, Uncaught syntax error, Unexpected token?

The following code is giving me an error in the chrome developer tools:
"uncaught syntax error- unexpected token"
Specifically, the Errors come up in the populate header function at
var notraw = JSON.parse(arrayraw)
and in the first if statement, at
parsed = JSON.parse(retrieved); //var test is now re-loaded!
These errors haven't come up in previous iterations. Does anyone know why?
// This statement should be ran on load, to populate the table
// if Statement to see whether to retrieve or create new
if (localStorage.getItem("Recipe") === null) { // if there was no array found
console.log("There was no array found. Setting new array...");
//Blank Unpopulated array
var blank = [
["Untitled Recipe", 0, 0]
];
// Insert Array into local storage
localStorage.setItem("Recipe", JSON.stringify(blank));
console.log(blank[0]);
} else {
console.log("The Item was retrieved from local storage.");
var retrieved = localStorage.getItem("Recipe"); // Retrieve the item from storage
// test is the storage entry name
parsed = JSON.parse(retrieved); //var test is now re-loaded!
// we had to parse it from json
console.log(parsed)
}
// delete from array and update
function deletefromarray(id) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
console.log(notraw[id])
notraw.splice(id, 1);
localStorage.setItem("Recipe", JSON.stringify(notraw));
}
// This adds to local array, and then updates that array.
function addtoarray(ingredient, amount, unit) {
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.push([ingredient, amount, unit]);
localStorage.setItem("Recipe", JSON.stringify(notraw));
var recipeid = notraw.length - 1
console.log("recipe id:" + recipeid)
}
//The calculation function, that gets the ingredients from the array, and calculates what ingredients are needed
function calculate(multiplier) {
alert("Calculate function was called")
var length = recipearray.length - 1;
console.log("There are " + length + " ingredients.");
for (i = 0; i < length; i++) {
console.log("raw = " + recipearray[i + 1][1] + recipearray[i + 1][2]);
console.log("multiplied = " + recipearray[i + 1][1] / recipearray[0][2] * multiplier + recipearray[i + 1][2]);
}
}
// The save function, This asks the user to input the name and how many people the recipe serves. This information is later passed onto the array.
function save() {
var verified = true;
while (verified) {
var name = prompt("What's the name of the recipe?")
var serves = prompt("How many people does it serve?")
if (serves === "" || name === "" || isNaN(serves) === true || serves === "null") {
alert("You have to enter a name, followed by the number of people it serves. Try again.")
verified = false;
} else {
alert("sucess!");
var element = document.getElementById("header");
element.innerHTML = name;
var header2 = document.getElementById("details");
header2.innerHTML = "Serves " + serves + " people"
calculate(serves)
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
notraw.splice(0, 1, [name, serves, notraw.length])
localStorage.setItem("Recipe", JSON.stringify(notraw))
return;
}
}
}
// the recipe function processes the inputs for the different ingredients and amounts.
function recipe() {
// Declare all variables
var ingredient = document.getElementById("ingredient").value;
var amount = document.getElementById("number").value;
var unit = document.getElementById("unit").value;
var count = "Nothing";
console.log("Processing");
if (isNaN(amount)) {
alert("You have to enter a number in the amount field")
} else if (ingredient === "" || amount === "" || unit === "Select Unit") {
alert("You must fill in all fields.")
} else if (isNaN(ingredient) === false) {
alert("You must enter an ingredient NAME.")
} else {
console.log("hey!")
// console.log(recipearray[1][2] + recipearray[1][1])
var totalamount = amount + unit
edit(ingredient, amount, unit, false)
insRow(ingredient, totalamount) // post(0,*123456*,"Fish")
}
}
function deleteRow(specified) {
// Get the row that the delete button was clicked in, and delete it.
var inside = specified.parentNode.parentNode.rowIndex;
document.getElementById('table').deleteRow(inside);
var rowid = inside + 1 // account for the first one being 0
console.log("An ingredient was deleted by the user: " + rowid);
// Remove this from the array.
deletefromarray(-rowid);
}
function insRow(first, second) {
//var first = document.getElementById('string1').value;
//var second = document.getElementById('string2').value;
// This console.log("insRow: " + first)
// Thisconsole.log("insRow: " + second)
var x = document.getElementById('table').insertRow(0);
var y = x.insertCell(0);
var z = x.insertCell(1);
var a = x.insertCell(2);
y.innerHTML = first;
z.innerHTML = second;
a.innerHTML = '<input type="button" onclick="deleteRow(this)" value="Delete">';
}
function populateheader() {
// Populate the top fields with the name and how many it serves
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
var element = document.getElementById("header");
element.innerHTML = notraw[0][0];
var header2 = document.getElementById("details");
// if statement ensures the header doesn't say '0' people, instead says no people
if (notraw[0][1] === 0) {
header2.innerHTML = "Serves no people"
} else {
header2.innerHTML = "Serves " + notraw[0][1] + " people"
}
console.log("Now populating Header, The Title was: " + notraw[0][0] + " And it served: " + notraw[0][1]);
}
function populatetable() {
console.log("Now populating the table")
// Here we're gonna populate the table with data that was in the loaded array.
var arrayraw = localStorage.getItem("Recipe")
var notraw = JSON.parse(arrayraw)
if (notraw.length === 0 || notraw.length === 1) {
console.log("Array was empty.")
} else {
var count = 1;
while (count < notraw.length) {
amount = notraw[count][1] + " " + notraw[count][2]
insRow(notraw[count][0], amount)
console.log("Inserted Ingredient: " + notraw[count][0] + notraw[count][1])
count++;
}
}
}

Why am I getting NaN in my local file but my fiddle is fine

I'm struggling to see why I'm getting NaN in my local file, but in my fiddle it works perfectly.
I've checked to see if I've left out any id's in the HTML but it all looks in order. I can't see why it is returning NaN.
Here is a part of my JavaScript which I think is causing the problem:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value) || 0.00,
delivery = parseFloat(document.getElementById("delivery").value),
total = amount + delivery,
fixedrate = total / 100 * 12.2,
grandtotal = fixedrate + total;
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
}
// handle the due date
var dayNames = new Array("Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday");
var monthNames = new Array("January","February","March","April","May","June","July", "August","September","October","November","December");
var todayPlus30 = new Date();
todayPlus30.setDate(todayPlus30.getDate()+30)
var dateStr = (dayNames[todayPlus30.getDay()] + ", " + monthNames[todayPlus30.getMonth()+1] + " " + todayPlus30.getDate() + ", " + todayPlus30.getFullYear());
$('#date').html(dateStr);
$(function(){
document.getElementById("amount").onchange =
document.getElementById("delivery").onchange = updateCost;
});
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
$(function(){
$("#amount").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if (".1234567890NOABC".indexOf(chr) < 0)
return false;
});
});
$("#amount").blur(function() {
var input = $(this).val();
if (/^\d*\.?\d{0,2}$/.test(input)) {
var amount = parseFloat(input);
if (amount < 40 || amount > 200) {
$("span.paymentalert").html("Your payment must be between £40 and £200");
} else {
$("span.paymentalert").html("");
}
} else {
$("span.paymentalert").html("Your payment must be a number");
}
});
Try this function like:
function updateCost() {
var amount = parseFloat(document.getElementById("amount").value) || 0.00;
var delivery = document.getElementById("delivery").value;
if(delivery !='select' && delivery)
{
delivery=parseFloat(delivery);
}
else
{
delivery=0.00;
}
var total = amount + delivery;
var fixedrate = total / 100 * 12.2;
var grandtotal = fixedrate + total;
document.getElementById("amountdiv").innerHTML = amount.toFixed(2);
document.getElementById("deliverydiv").innerHTML = delivery.toFixed(2);
document.getElementById("total").innerHTML = total.toFixed(2);
document.getElementById("fixedrate").innerHTML = fixedrate.toFixed(2);
document.getElementById("grandtotal").innerHTML = grandtotal.toFixed(2);
}
Also you have written onchange function 2 times
$(document).ready(function(){
$('#amount').change(function(){ updateCost(); });
$('#delivery').change(function(){ updateCost(); });
});
You can remove it
$(function(){
document.getElementById("amount").onchange =updateCost;
document.getElementById("delivery").onchange = updateCost;
});
Looks like you have missed something
$(function(){
document.getElementById("amount").onchange = // something should be here with statement end
document.getElementById("delivery").onchange = updateCost;
});
see the comment part, you have missed the amount initialization and termination of the statement too.
I hope this will solve the problem with NAN :)

Categories

Resources