JavaScript - Calculating Shipping With If/else And Function
I am having difficulty getting the following assignment to run properly:
Many companies charge a shipping and handling charge for purchases. Create a Web page that allows a user to enter a purchase price into a text box and includes a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling charge of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minmum shipping and handling charge. The formula for calculating a percentage is price * percent / 100. For example, the formula for calculating 10% of a $50.00 purchase price is 50 * 10 / 100, which results in a shipping and handling charge of $5.00. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. Save the document as CalcShipping.html. This is what I have after working on it round and round for 4 hours yesterday: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Calculate Order</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="js_styles.css" type="text/css" /> <script type="text/javascript"> /* <![CDATA[ */ function applyShipping(shipping) { if (purchase > 25.00) shipping = purchase * 10 / 100; } /* ]]> */ </script> </head> <body> <script type="text/javascript"> /* ![CDATA[ */ document.write("<h1>Purchase Plus Shipping</h1>"); /* ]]> */ </script> <script type="text/javascript"> /* <![CDATA[ */ var purchase=window.prompt("Please Enter Your purchase amount"); var shipping = 1.50; applyShipping(); document.write ("<p>The price entered was $" + (purchase) + "</p>"); document.write ("<p>Shipping and Handling $" + (shipping) + "</p>"); var totalPrice = purchase + shipping; document.write ("<p>Your total price is $" + (totalPrice) + "</p>"); // window.alert("Your total price is $" + (totalPrice) + );// /* ]]> */ </script> </body> </html> Similar TutorialsThe question in the book says: Many companies normally charge a shipping and handling fee for purchases. Create a Web page that allows a user to enter a purchase price into a text box; include a JavaScript function that calculates shipping and handling. Add functionality to the script that adds a minimum shipping and handling fee of $1.50 for any purchase that is less than or equal to $25.00. For any orders over $25.00, add 10% to the total purchase price for shipping and handling, but do not include the $1.50 minimum shipping and handling fee. The formula for calculating a percentage is price*percent/100. After you determine the total cost of the order (purchase plus shipping and handling), display it in an alert dialog box. This is what I have so far, it comes up with the text box, but when the price is entered it doesn't come back with an answer. Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="js_styles.css" type="text/css" /> <title>Calculating Shipping & Handling</title> <script type="text/javascript"> /* ![CDATA[ */ function getShipping(); { if (price <= 25.00) shipping = 1.50 else if(price > 25.00) shipping = (price * (10/100)); } /* ]]> */ </script> </head> <body> <script type="text/javascript"> /* ![CDATA[ */ document.write("<h1>Purchase Price with Shipping</h1>"); /* ]]> */ </script> <script type="text/javascript"> /* <![CDATA[ */ var price=prompt("What is your purchase price?"); getShipping(); document.write ("<p>The purchase price entered is $" + (price) + "</p>"); document.write ("<p>Shipping is $" + (shipping) + "</p>"); var total = price + shipping; document.write("Your total price with shipping is $ " + (total) + ""); /* ]]> */ </script> </body> </html> Right now this javascript shopping cart works to 1. charge shipping based on the item, 2. the destination country, 3. it combines shipping for a quantity over 1 of the SAME item. Each item has 2 different possible shipping charges. I am trying to get the javascript to check the shopping cart to see what item in the cart has the highest possible shipping charge, charge that amount to that item, and charge the lowest possible shipping charge on all other items in the cart. If item A is purchased alone shipping is $5.00. If purchased with item B, which costs $10.00 to ship alone, the $10.00 is charged for item B and only $3.00 for item A. Because item B had the higher shipping charge at a quantity of one. I have tried adding various things like me.items[current], item.shipping, me.shipping, this.shipping, shipping_Cost, and other things next to the second && in the part of the script that shows the country. I have also tried adding && if (me.whatever) and && if (item.whatever) and similar things at the beginning of the script next to if (this.country). I have found the parts of the script that pertain to cart items and to updating the shopping cart. Now I am stuck. The javascript is in 2 parts. One part goes in the item page, which I will post first. The second part goes in an external javascript file which I will post at the bottom. In between there is the part that shows the shopping cart. It isn't part of the javascript. Code: <script type="text/javascript" src="simpleCart.js"></script> <script type="text/javascript"> <!-- simpleCart.checkoutTo = PayPal; simpleCart.email = "my Paypal email address"; simpleCart.cartHeaders = ["Name" , "Price" , "Quantity" , "remove" ]; CartItem.prototype.shipping=function(){ // we are using a 'country' field to calculate the shipping, // so we first make sure the item has a country if(this.country){ if( this.country == 'United States' && this.quantity == '1'){ return this.quantity*5.00; } else if( this.country == 'United States' && this.quantity >= '2') { return this.quantity*3.00; } else if( this.country == 'Belgium' && this.quantity == '1') { return this.quantity*12.00; } else if( this.country == 'Belgium' && this.quantity >= '2') { return this.quantity*9.00; else { return this.quantity*0.00; } } else { // use a default of $0.00 per item if there is no 'country' field return this.quantity*0.00; } } // --></script> Code: <div style="display:block;"></div> <div>SHOPPING CART</div> <div class="cartHeaders"></div><br><br><br> <div class="simpleCart_items"></div> <div id="totals"> Item Total: <span class="simpleCart_total"></span><br>Shipping Total: <span class="simpleCart_shippingCost"></span><br>Tax: <span class="simpleCart_taxCost"></span><br>Final Total: <span class="simpleCart_finalTotal"></span> </div> <br><br><br><br> <br><br> <a href="javascript:;" class="simpleCart_empty">Empty Shopping Cart</a><br><br> <a href="javascript:;" class="simpleCart_checkout">Checkout Through Paypal</a> </div></div> separate javascript file is here http://simplecartjs.com/documentation.html I am trying to combine shipping across different items in a javascript shopping cart. I can comine shipping based on how many items are in the cart, and characteristics of the item being added. But not both. I need the script to combine shipping based on how many items are in the cart, as well as the item name of the item being added to the cart. I assume I need to check the cart quantity in 1 function, then have it call 1 of 2 other functions based on how many items are in the cart. The 2nd function would charge the shipping based on the item name. I don't know if the code is wrong, and where I should put the 2 additional functions I am adding. It isn't working though. I am adding 2 ways I have tried below. Code: me.shipping = function(){ switch(me.quantity){ case '0': return 0; break; case '1': return oneItemInCart(); break; default: otherNumber; return moreThanOneItemInCart(); break; } function oneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return 4.39 else if(item.name.match = "Glitter") return 5.00 else return quantity*0.00; } } function moreThanOneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return item.quantity*3.00-3.00+4.39 if(item.name.match = "Glitter") return item.quantity*4.00-4.00+5.00 else return quantity*0.00; } } Code: me.shipping = function(){ if( parseInt(me.quantity,10)===0 ) return 0; else if( parseInt(me.quantity,10)===1) return oneItemInCart(); else if( parseInt(me.quantity,10) > 1) return moreThanOneItemInCart(); else return quantity*0.00; function oneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return 4.39 else if(item.name.match = "Glitter") return 5.00 else return quantity*0.00; } } function moreThanOneItemInCart(); { if(item.name) { if(item.name.match = "Cricut Cartridge") return item.quantity*3.00-3.00+4.39 if(item.name.match = "Glitter") return item.quantity*4.00-4.00+5.00 else return quantity*0.00; } } Here is the original document - the part I edited is the me.shipping part http://simplecartjs.com/ Hello all, I am trying to copy the billing information to be the same as the shipping information when they select the checkbox. Everything seems to work except for the State field which is a drop down. Depending on what country they select, the state field will automatically populate. Does anyone know how I can copy the billing state to be the same as shipping as well? Text file attached. Thanks in advance. Hi, PanM here. Trying to build a website to help my cousin sell his beautiful art. I am using a free web page at weebly.com and they have an option to use either PayPal or Google Checkout to put in shipping costs and go to the cart checkout. However, haven't evaluated Google yet, but PayPal does not do what I want. You have to put in various shipping prices and then it doesn't relate to the state or country unless you select all states, or anyway that's how I see it. I have found one on the net that wants $5 per month, but I am trying to do this for free. UPS, FedEx, and USPS have API's that can probably work, but I would prefer a HTML file or Javascript file in the page on my site. Can anyone help with this problem? Please. Thanks, PanM I now have the calculation, topic can be closed! thanks Hi, I am trying to write a script that will take a date of birth and another date and, if the person was over 75 years old on the createdDate, return "true" (otherwise return "false"). Unfortunately my code doesn't seem to return either 'true' or 'false'! Any help would be grately appreciated. The code is: Code: var dateofBirth="30/10/1982"; var createdDate="01/12/2010"; var sd = dateofBirth.split('/'); var dob = new Date(sd[2],sd[1],sd[0]); sd = createdDate.split('/'); var submit = new Date(sd[2],sd[1],sd[0]); var age=submit-dob; var ageYears=Math.floor((((age/3600000)/24)+1)/365.25); if(ageYears>75) document.write("true") else document.write("false") ; to be honest I have no idea where to start, i have a table, with 2 numeric values at the minute, if the checkbox is selected I want the total price to be shown? Any help to get me started would be great! this is the form I have with the numeric values Code: <form id="calculation" action="#" method="post"> 100 <input type="checkbox" name="check1" value="100" onClick='total_cost()'/> 120 <input type="checkbox" name="check2" value="200" onClick='total_cost()'/> Total cost<input type="text" name="total" id="total" readonly="readonly" /> onClick='total_cost()' is referring to the javascript function where I just don't know where to start? Hello everyone. Below is code I have developed for a simple spreadsheet. The issue I am having is that when I total a row or column using "=sum(a1:a5)" and then I try and total another row and add the sum of the two totals together I am not getting a valid response back. All I am presented with is a "0" in the column cell. Here is the code in two files and have also included an attachment of the whole project: tablepage.js Code: // JavaScript Document var tblRows = 20; var tblColumns = 10; var tblArray = new Array(tblRows); var p = window.parent; // Initial page event handler function initPage() { p.refAssignCellFromTextbox = assignCellFromTextbox; for (var i = 0; i < tblArray.length; i++) { tblArray[i] = new Array(tblColumns); for (var j = 0; j < tblArray[i].length; j++) tblArray[i][j] = "0"; } recalculate(); } // Recalculate cell values function recalculate() { for (var i = 0; i < tblRows; i++) { for (var j = 0; j < tblColumns; j++) { if (tblArray[i][j].indexOf("=SUM") != -1) { calculateCell(i, j); } } } } // Click cell event handler function clickCell(cellRef) { thisRef = cellRef; var cellID = cellRef.id; var row = parseFloat(cellID.substr(0, 3)) - 1; var column = parseFloat(cellID.substr(3, 2)) - 1; var cellValue = tblArray[row][column]; var tokenArray = getFormula(cellValue); if (tokenArray != null) p.assignTextboxFromArray(cellValue); else p.assignTextboxFromCell(cellRef); } // Update cell from textbox function assignCellFromTextbox(tblValue) { if (thisRef != undefined) { if (tblValue == "") { tblValue = "0"; } var tokenArray = getFormula(tblValue); if (tokenArray != null) { assignArray(thisRef.id, tblValue.toUpperCase()); } else { if (!isFloat(tblValue)) { parseValue = tblValue.replace(/[^0-9]/g, ''); tblValue = parseValue; } assignArray(thisRef.id, tblValue); if (tblValue == "0") thisRef.innerText = ""; else thisRef.innerText = tblValue; } recalculate(); } } // Determines if a user entered a formula function getFormula(tblValue) { var pattern = /[:|\(|\)]/; var ar = tblValue.split(pattern); var sum = ar[0].toUpperCase(); if (ar.length < 3) return null; else if (sum != "=SUM") { return null; } else { return ar; } } function assignArray(cellID, tblValue) { var row = parseFloat(cellID.substr(0, 3)); var column = parseFloat(cellID.substr(3, 2)); tblArray[row - 1][column - 1] = tblValue; } function calculateCell(row, column) { var tokenArray = getFormula(tblArray[row][column]); if (tokenArray != null) { var fromColumn = tokenArray[1].substr(0, 1); var fromRow = tokenArray[1].substr(1, tokenArray[1].length - 1); var toColumn = tokenArray[2].substr(0, 1); var toRow = tokenArray[2].substr(1, tokenArray[2].length - 1); var fromRowIndex = parseFloat(fromRow) - 1; var fromColIndex = fromColumn.charCodeAt(0) - 65; var toRowIndex = parseFloat(toRow) - 1; var toColIndex = toColumn.charCodeAt(0) - 65; var sumTotal = 0; for (var i = fromRowIndex; i <= toRowIndex; i++) { for (var j = fromColIndex; j <= toColIndex; j++) { if (isFloat(tblArray[i][j])) sumTotal += parseFloat(tblArray[i][j]); } } var cellID = fillField((row + 1).toString(), 3) + fillField((column + 1).toString(), 2); document.getElementById(cellID).innerText = sumTotal; } } function isFloat(s) { var ch = ""; var justFloat = "0123456789."; for (var i = 0; i < s.length; i++) { ch = s.substr(i, 1); if (justFloat.indexOf(ch) == -1) return false; } return true; } function fillField(s,n) { var zeros = "0000000000"; return zeros.substring(0, n - s.length) + s; } spreadsheet.js Code: // JavaScript Document var refAssignCellFromTextbox; var nCharsAllowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890.=(): "; // Event Handler function initPage() { document.getElementById("TableFrame").style.top = "50px"; document.getElementById("TableFrame").src = "tablepage.html"; } // Updates text field when a user clicks on a particular field from with the spreadsheet function assignTextboxFromCell(cValue) { document.getElementById("fieldEntry").value = cValue.innerText; document.getElementById("fieldEntry").focus(); } // Assists tablepage.js with updating a value from a 2D array function assignTextboxFromArray(aValue) { document.getElementById("fieldEntry").value = aValue; document.getElementById("fieldEntry").focus(); } // Used when a user presses a key to update text field function filterText() { if (window.event.keyCode != 13) { if (!nCharOK(window.event.keyCode)) window.event.keyCode = null; } else { window.event.keyCode = null; refAssignCellFromTextbox(document.getElementById("fieldEntry").value); } } // Checks to see if character entered falls within our preset function nCharOK(c) { var ch = (String.fromCharCode(c)); ch = ch.toUpperCase(); if (nCharsAllowed.indexOf(ch) != -1) return true; else return false; } // Clears all data from the screen function clearPage() { initPage(); document.getElementById("fieldEntry").value = ""; } // Add a row to the table function addRow(frmTable) { var table = document.getElementById(frmTable); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); // cell2.innerHTML = rowCount + 1; // Unless this is going to be completely dynamic // the rest of the table code would have had to be // entered in statically. Not happening. } // Delete a row from the table function deleteRow(frmTable) { try { var table = document.getElementById(frmTable); var rowCount = table.rows.length; for(var i=0; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { table.deleteRow(i); rowCount--; i--; } } } catch(e) { alert(e); } } Hi, There are two text boxes in a HTML form. The first text box takes the time when the user starts to work on a project. The second box takes the time when the user stops working on that project. Now, I would like to calculate the total time worked on that project for that user. That is (stop time - start time). I tried few things without success. Any help will be appreciated. I thought this would be simple. Evidently it's not With the date below (and it being 11.45 on the 27th as I type this), the counter returns the correct number of hours/mins/seconds remaining, but shows 33 days. It seems to be adding 31 days to the count, but I can't figure out where Code: function countdown(){ var bigday = new Date(2009,10,29,14,30,0,0); var today = new Date(); var difference = bigday - today; var remaining = Math.floor(difference/1000); // want seconds, not milliseconds var days = Math.floor(remaining/86400); remaining = remaining % 86400; var hours = Math.floor(remaining/3600); remaining = remaining % 3600; var minutes = Math.floor(remaining/60); remaining = remaining % 60; seconds = Math.floor(remaining); var out = days + " days, " + hours + " hours, " + minutes + " minutes and " + seconds + " seconds left..."; $('#countdown').text(out); setTimeout(countdown, 1000); } Hey there, first time poster. I am trying to create an order with the ability to dynamically self total the sum of the selected items but also be able to add a 25% labor fee having it be at least $90. So if someone buys $300 worth of items the labor charge would be $75 but it would be automatically bumped to $90. heres the existing code: PHP Code: * Calculates the payment total with quantites * @param {Object} prices */ countTotal: function(prices){ var total = 0; $H(prices).each(function(pair){ total = parseFloat(total); var price = parseFloat(pair.value.price); if ($(pair.key).checked) { if ($(pair.value.quantityField)) { price = price * parseInt($(pair.value.quantityField).getSelected().text, 10); } total += price; } }); if (total === 0) { total = "0.00"; } if ($("payment_total")) { $("payment_total").update(parseFloat(total).toFixed(2)); } }, /** * Sets the events for dynamic total calculation * @param {Object} prices */ totalCounter: function(prices){ $H(prices).each(function(pair){ $(pair.key).observe('click', function(){ JotForm.countTotal(prices); }); if ($(pair.value.quantityField)) { $(pair.value.quantityField).observe('change', function(){ $(pair.key).checked = true; JotForm.countTotal(prices); }); } }); }, I'm trying to find the difference between 2 times. Time formats are 00:00:00.0 For example... var t1 = "00:07:51.0"; var t2 = "00:53:21.0"; How do I calculate the difference between those 2 times? TIA. Hi! I'm very new to javascript and a bit stuck with trying to calculate values from functions together. Let's say I have three functions. Each function is given a value and the goal is to calculate all the values together in a variable. This is what I have so far: Code: function numberAdd1 () { addValue = 1; return.addValue; } function numberAdd2 () { addValue = 2; return.addValue; } function numberAdd3 () { addValue = 3; return.addValue; } How would I now calculate the return value of each funtion together and store the result in a variable? Hi guys Sorry about the vague Title, but I really do not know anything about JavaScript. Infact I only know very VERY basic html... So I hope you can help me. I am trying to create a form like this: Where the blue is user entered, and red is results. Apparently I can't do that with my basic html skills but javascript can? The Formula via excel for 'Generic SOP' is =100-((ABS(A3-10))+(ABS(B3-10))+(ABS(C3-10))+(ABS(D3-10))+(ABS(E3-10))+(ABS(A6-10))+(ABS(B6-10))+(ABS(C6-10))+(ABS((D6-20)/2))+(ABS(E6-10))) and for 'SOP' =100-((ABS(A3-10)*1.5)+(ABS(B3-10)*1)+(ABS(C3-10)*1)+(ABS(D3-10)*2)+(ABS(E3-10)*1)+(ABS(A6-10)*0.5)+(ABS(B6-10)*0.5)+(ABS(C6-10)*1)+(ABS(D6-20)/2)+(ABS(E6-10)*0.5)) I would also like a drop down box that allows me to choose different variables that changes the 'SOP' formula slightly.. but maybe I should leave that out for now.. I hope that was understandable and if this is too much to ask just tell me to get nicked and go learn how to code myself.. Thankyou for looking guys Can someone please assist. I am trying to create a order form that auto calculates my totals as I enter the quantities. It comes up with Not a Number(NaN). Below are snippets from my code this is obviously in a <form>: HTML: Code: <!-- Row 3, Col 3 purchase boxes --> <td colspan="1" height="120" align="left"> <input style="margin-left: 60px" type="text" name="bed_359" size="3" maxlength="3" onchange="calculateValue(this.form)" /> R359</td></tr> <!-- Row 10, Col 2 Order Value Box--> <td colspan="1" align="left"><input style="margin-left: 60px" type="text" name="total" size="10" onfocus="this.form.elements[0].focus()" /> </td></tr> javaScript: Code: // Function to calculate order value function calculateValue(orders) { var orderValue = 0; var value = 0; var itemPrice = 0; var itemQuantity = 0; // Run through all the product fields for(var i = 0; i < orders.elements.length; ++i) { // Get the current field formField = orders.elements[i]; // Get the fields name formName = formField.name; // Items price extracted from name itemPrice = parseFloat(formName.substring(formName.lastIndexOf("0") + 1)); // Get the Quantity itemQuantity = parseInt(formField.value); // Update the OrderValue if(itemQuantity >= 0) { value = itemQuantity * itemPrice; orderValue += value; } } // Display the total orders.total.value = orderValue; } Please help its probably something simple. Calculating the difference between two dates in JavaScript is relatively straightforward, provided you choose the right Date methods to work with. Whichever way you get there.... see this http://www.tutorials99.com/tutorials...aScript/page_1 hey guys, happy new year! , I was wondering how to calculate an outcome/number through a combination of 4 drop down menus (drop down menu's 1 and 2 combine to form a specific value and menu's 3 and 4 combine to form a specific value), example ; 1st drop down menu (1*) = a,b,c,d,e 2nd drop down menu (2*) = 5,4,3,2,1 3rd drop down menu (3*)= a,b,c,d,e 4th drop down menu (4*)= 5,4,3,2,1 Example of drop down menu layout - View image: example a->e = low to high (value) predominant value so b5>a1 ; d5>c1 5->1 = low to high (value) Then the calculation involves the 1st and 2nd menu to form 1 value, so c3, e4 etc and the 3rd and 4th menu unite to form 1 value that is different from the first; c2, e3 So (1*2*) b3 ; (3*4*) b1 = x value Also the value from 1*2* menu must be lower than value from menu 3*4*; so you cannot input 1*2* c4 ; 3*4* c5 /or b1 (so once the first menu is selected, the 3rd and 4th menu's wont show anything lower) I am not sure the best way about going to calculate the value for x (generated from the menu combinations) however I can outline the values for each combination as it involves simple addition; Example; 1*2* c5 ; 3*4* c4 = 39 Example; 1*2* c4 ; 3*4* c3 = 43 Example; 1*2* c3 ; 3*4* c2 = 44 Example; 1*2* c2 ; 3*4* c1 = 49 Therefore 1*2* c5 ; 3*4* c1 = 175 (c5>c4 + c4>c3 + c3>c2 + c2>c1 = 175) Starting from a5 to e1 the values are as follows; [(a5->a4 = 17),17,17,17],[(a1->b5 = 22.5),22.5,22.5,22.5],[39.6,39.6,43,44],[49,56.7,56.7,60],[69,76.5,90,161],[189.5,216,(e2->e1 = 246.5),no further value (no f5)] If you could help me out that would be amazing, appreciate any help/feedback in advance! |