JavaScript - Help With Calculating Shopping Total With A Quantity Textbox
I've been given this ridiculous assignment where I have to create a shopping web page. I really need help finding the javascript codes that will allow the user to update their total as they enter the quantities of the different products in the assigned text boxes.
I don't even know where to start because we were never taught how to do this in class! Similar TutorialsFolks, I am trying to calculate the total of fields on a web form. I have multiple rows of 10 fields with a total for each. Each row comes from a different record in a database. I am only showing 2 fields of the 10 for simplicity. The name and id of each field looks like "Q300_1" onchange="update(Q300)" "Q300_2" onchange="update(Q300)" "Q300_t" "Q301_1" onchange="update(Q301)" "Q301_2" onchange="update(Q301)" "Q301_t" My current attempt at the script looks like: [CODE] <script type="text/javascript"> function update(item) { var itemt=item + "_t"; var item1=item + "_1"; var item2=item + "_2"; document.myform[itemt].value = (document.myform[item1].value -0) + (document.myform[item2].value -0); } </script> [CODE] It does not work and I get Error: Q301 is not defined in the Firefox error console. Hi all, I am trying to have a form calculate total using this script, works OK until the total reaches 99 from there on it only returns 2 figures. Also it won't work if I complete the dollar value (i.e add .00) Anyone tell me where I am going wrong? Code: <script type="text/javascript"> function startCalc(){ interval = setInterval("calc()",1); } function calc(){ q1 = document.apply.appfee.value = 11; q2 = document.apply.memfee.value = 20; q3 = document.apply.levy.value; q4 = document.apply.donation.value; document.apply.total.value = (q1*1) + (q2*1) + (q3*1) + (q4*1) } function stopCalc(){ clearInterval(interval); } </script> This is the form: Code: <form name="apply" action="" method="post" onsubmit="return validate(apply)"> <table style="width:680px;"> <tr> <td style="text-align:right; white-space:nowrap; width:300px;">Application Fee:</td> <td style="text-align:left; white-space:nowrap; width:441px">$<input type="text" readonly value="" name="appfee" style="width:17px; border:0; font:11px verdana; color:#006;margin-bottom:5px;"></td> </tr> <tr> <td style="text-align:right; white-space:nowrap; width:300px;">Annual Memebership Fee:</td> <td style="text-align:left; white-space:nowrap;">$<input type="text" readonly value="" name="memfee" style="width:17px; border:0; font:11px verdana; color:#006;margin-bottom:5px;"></td> </tr> <tr> <td style="text-align:right; white-space:nowrap; width:300px;">* Optional Annual Levy:</td> <td style="text-align:left;"> $<select name="levy" onFocus="startCalc();" onBlur="stopCalc();"> <option selected>0</option> <option value="22">22</option> <option value="44">44</option> <option value="66">66</option> <option value="88">88</option> <option value="110.00">110</option> </select> </td> </tr> <tr> <td style="text-align:right; white-space:nowrap; width:300px;">* Optional Donation:</td> <td>$<input type="text" name="donation" value="" onFocus="startCalc();" onBlur="stopCalc();" style="font:11px verdana; color:#006;margin-bottom:5px; width:80px;"></td> </tr> <tr> <td style="text-align:right; white-space:nowrap; width:300px;"><b>TOTAL:</b></td> <td white-space:nowrap;><b>$<input type="text" name="total" style="width:17px; border:0; font:bold 11px verdana; color:#006;margin-bottom:6px;"></b></td> </tr> </table> </form> I have everything working up to this point but when I try and put the math equation into my script section, I get multiple error and cannot figure out how to get the function to return the actual total rental cost. If you could please look at what I have, your opinions would be greatly appreciated. Thank you. Below is the code with the math function at the end of the script section in the heading which I seem to be receiving error on. Any help is greatly appreciated. Thanks. Code: <!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> <!-- Brooks Rogalski December 6, 2010 --> <title>ABC Outdoor Sports</title> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <script type = "text/javascript"> /* <![CDATA[ */ //image slideshow function var interval = 4000; // delay between rotating images var random_display = 1; // 0 = no, 1 = yes var pause = false; var image_index = 0; image_list = new Array(); image_list[image_index++] = new imageItem("fishing.jpg"); image_list[image_index++] = new imageItem("biking.jpg"); image_list[image_index++] = new imageItem("climbing.jpg"); image_list[image_index++] = new imageItem("kayaking.jpg"); image_list[image_index++] = new imageItem("scuba.jpg"); var number_of_image = image_list.length; function imageItem(image_location) { this.image_item = new Image(); this.image_item.src = image_location; } function get_ImageItemLocation(imageObj) { return(imageObj.image_item.src) } function generate(x, y) { var range = y - x + 1; return Math.floor(Math.random() * range) + x; } function getNextImage() { if (pause == true) return; if (random_display) { image_index = generate(0, number_of_image-1); } else { image_index = (image_index+1) % number_of_image; } var new_image = get_ImageItemLocation(image_list[image_index]); return(new_image); } function rotateImage(place) { var new_image = getNextImage(); document[place].src = new_image; var recur_call = "rotateImage('"+place+"')"; setTimeout(recur_call, interval); } //check valid pickup date function checkValidPDate(which) { which = which.replace(/[-:,\.]/g,"/"); which = which.replace(/[^0-9\/]/,""); var dt = which.split("/"); var yr = dt[2]; if (!yr) {yr = 9999} if (yr.length == 2) {yr = parseInt(yr) + 2000} if ((yr < 2010) || ( yr > 2020)) { alert ("Invalid Year or Date Format!"); document.getElementById('dateIn').value = ""; // clear the field setTimeout("document.getElementById('dateIn').focus()", 25); // and refocus on it return false; } var mm = dt[0]-1; var mmx = dt[0]; var dd = dt[1]; var nd = new Date(); nd.setFullYear(yr,mm,dd); // YYYY,MM(0-11),DD var ndmm = nd.getMonth(); if (ndmm != mm) { alert (mmx + "/" + dd + "/" + yr + " is NOT a Valid Date!"); document.getElementById("dateIn").value = ""; // clear the field setTimeout("document.getElementById('dateIn').focus()", 25); // and refocus on it return false; } else { alert (mmx + "/" + dd + "/" + yr + " is a Valid Date!"); // for testing } var reserveDate = new Date(yr,mm,dd); var mydate = new Date(); mydate.setDate(mydate.getDate()+2); // Two CLEAR days ahead - NB mydate is HRS:MNS:SECS so same date is a problem if (reserveDate < mydate) { window.alert("Reservations need to be at least two clear days in advance."); document.getElementById("dateIn").value = ""; // clear the field setTimeout("document.getElementById('dateIn').focus()", 25); // and refocus on it } } //check valid return date function checkValidRDate(which) { which = which.replace(/[-:,\.]/g,"/"); which = which.replace(/[^0-9\/]/,""); var dt = which.split("/"); var yr = dt[2]; if (!yr) {yr = 9999} if (yr.length == 2) {yr = parseInt(yr) + 2000} if ((yr < 2010) || ( yr > 2020)) { alert ("Invalid Year or Date Format!"); document.getElementById('dateOut').value = ""; // clear the field setTimeout("document.getElementById('dateOut').focus()", 25); // and refocus on it return false; } var mm = dt[0]-1; var mmx = dt[0]; var dd = dt[1]; var nd = new Date(); nd.setFullYear(yr,mm,dd); // YYYY,MM(0-11),DD var ndmm = nd.getMonth(); if (ndmm != mm) { alert (mmx + "/" + dd + "/" + yr + " is NOT a Valid Date!"); document.getElementById("dateOut").value = ""; // clear the field setTimeout("document.getElementById('dateOut').focus()", 25); // and refocus on it return false; } else { alert (mmx + "/" + dd + "/" + yr + " is a Valid Date!"); // for testing } if(document.forms[0].returnDate.value <= document.forms[0].pickupDate.value){ window.alert("Please choose later date"); valid=false; return false; } } //validate form functions function validateForm() { var valid = true; //validate equipment if (document.forms[0].equipment.selectedIndex == 0) { window.alert("Please select your equipment type."); document.forms[0].equipment.focus(); return false; } //validate pick-up time hours if (document.forms[0].pickupHours.selectedIndex == 0) { window.alert("Please select the number of hours for pick-up time."); document.forms[0].pickupHours.focus(); return false; } //validate pick-up time minutes if (document.forms[0].pickupMinutes.selectedIndex == 0) { window.alert("Please select the number of minutes for pick-up time."); document.forms[0].pickupMinutes.focus(); return false; } //validate return time hours if (document.forms[0].returnHours.selectedIndex == 0) { window.alert("Please select the number of hours for return time."); document.forms[0].returnHours.focus(); return false; } //validate return time minutes if (document.forms[0].returnMinutes.selectedIndex == 0) { window.alert("Please select the number of minutes for return time."); document.forms[0].returnMinutes.focus(); return false; } //validate first name if (document.forms[0].firstName.value=="") { window.alert("Please enter your first name."); document.forms[0].firstName.focus(); valid = false; return valid; } //validate last name if (document.forms[0].lastName.value=="") { window.alert("Please enter your last name."); document.forms[0].lastName.focus(); valid = false; return valid; } //validate street address if (document.forms[0].street.value=="") { window.alert("Please enter your street address."); document.forms[0].street.focus(); valid = false; return valid; } //validate city if (document.forms[0].city.value=="") { window.alert("Please enter your city."); document.forms[0].city.focus(); valid = false; return valid; } //validate zip code if (document.forms[0].zip.value==""){ window.alert("Please enter your zip code."); document.forms[0].zip.focus(); valid=false; return valid; } var re5digit=/^\d{5}$/ if (document.forms[0].zip.value.search(re5digit)==-1){ window.alert("Please enter a 5 digit number") valid=false; return valid; } //validate date of birth if (document.forms[0].date.value == "'' || '(mm/dd/yyyy)'" ){ window.alert("Please enter your date of birth."); document.forms[0].birthDate.focus(); valid=false; return valid; } var reDateFormat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/ if(document.forms[0].date.value.search(reDateFormat)==-1){ window.alert("Please enter a standard format. [mm/dd/yyyy]") valid=false; return valid; } //check if over 18 var age; var input = document.forms[0].birthDate.value; var pyear = parseInt(input.substring(6,10)); var pmonth = parseInt(input.substring(0,2)) - 1; var pday = parseInt(input.substring(3,5)); if ( month < pmonth ){ age = year - pyear - 1; } else if ( month > pmonth ){ age = year - pyear; } else if ( month == pmonth ){ if ( day < pday ){ age = year - pyear - 1; } else if ( day > pday ){ age = year - pyear; } else if ( day == pday ){ age = year - pyear; } } if(age < 18){ window.alert('Attention: Under 18!'); valid=false; return valid; } //calculate total cost and diplay in window.confirm() dialog box var equip = document.forms[0].equipment.value var pDate = document.forms[0].pickupDate.value var pHours = document.forms[0].pickupHours.value var pMinutes = document.forms[0].pickupMinutes.value var rDate = document.forms[0].returnDate.value var rHours = document.forms[0].returnHours.value var rMinutes = document.forms[0].returnMinutes.value var pTime = pHours + pMinutes; var rTime = rHours + rMinutes; var total = (((rDate - pDate) - 1) * 24) * equip) + ((rTime + (24 - pTime)) * equip); var OK = window.confirm(" The total rental cost is $" + total + "\n Click OK to accept, Cancel to decline"); if (OK) {return true} else {return false} } /* ]]> */ </script> </head> <body onload = "rotateImage('rImage')"> <h1> ABC Outdoor Sports Equipment </h1> <img src="fishing.jpg" id="rImage" width="250" height="200" onmouseover = "pause=true;" onmouseout = "pause=false;"> <br/> <br/> <form onsubmit = "return validateForm();" action = "mailto:rogalskibf@gmail.com?subject=ABC Customer Reservation" method="post" enctype="text/plain"> <table border = "0"> <tr> <td> Equipment:<br/> <select name = "equipment"> <option value="unselected">Select Equipment Type</option> <option value = 20>Fishing Boat</option> <option value = 15>Kayak</option> <option value = 2>Mountain Bike</option> <option value = 10>Scuba Gear</option> </select> </td> </tr> <tr> <td> Pick-up Date: <br/> <input type = "text" id = "dateIn" name = "pickupDate" onchange = checkValidPDate(this.value)> </td> <td> Pick-up Time: <br/> <select name = "pickupHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "pickupMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> Return Date: <br/> <input type = "text" id = "dateOut" name = "returnDate" onchange = checkValidRDate(this.value)> </td> <td> Return Time: <br/> <select name = "returnHours"> <option value="unselected">hr</option> <option value = 7>07</option> <option value = 8>08</option> <option value = 9>09</option> <option value = 10>10</option> <option value = 11>11</option> <option value = 12>12</option> <option value = 13>13</option> <option value = 14>14</option> <option value = 15>15</option> <option value = 16>16</option> <option value = 17>17</option> </select> <select name = "returnMinutes"> <option value="unselected">min</option> <option value = 0>00</option> <option value = .5>30</option> </select> </td> </tr> <tr> <td> First Name: <br/> <input type = "text" name = "firstName"/> </td> <td> Last Name: <br/> <input type = "text" name = "lastName"/> </td> </tr> <tr> <td> Street: <br/> <input type = "text" name = "street"/> </td> <td> City: <br/> <input type = "text" name = "city"/> </td> <td> Zip:<br/> <input type = "text" name = "zip" maxlength = "5"/> </td> </tr> <tr> <td> Date of Birth: <br/> <input type = "text" name = "date" value = "(mm/dd/yyyy)"/> </td> </tr> <tr> <td colspan = "3" align = "center"> <input type = "submit" name = "submit" value = "Submit Reservation"/> <input type = "button" name = "cookies" value = "Store User Information"/> </td> </tr> </table> </form> </body> </html> For various reasons, I need the value of my drop down box options to contain size information rather than price. However I would like to be able to calculate a price for the items based on what size the user selects as well as the quantity. Below is the code I came up with (which doesn't work obviously) What can I do to get this to work for me? Thanks in advance for any help! Code: <head> <script type="text/javascript"> <!-- function calc(A,B,SUM) { var price = document.getElementById(A).extrainfo; var quantity = document.getElementById(B).value; document.getElementById(SUM).value = price * quantity; } //--> </script> </head> <body> <label>T-Shirt: <select name="T_SHIRT" id="T_SHIRT" onchange="calc('T_SHIRT','Tshirt_QTY','total');"> <option selected="selected">CHOOSE A SIZE </option> <option value="SIZE: SMALL" extrainfo="10.99">Small, 34/36 (S) </option> <option value="SIZE: MEDIUM" extrainfo="11.99">Medium, 38/40 (M) </option> <option value="SIZE LARGE" extrainfo="12.99">Large, 42/44 (L) </option> </select> </label> <label>QTY: <input type="text" id="Tshirt_QTY" name="Tshirt_QTY" onchange="calc('T_SHIRT','Tshirt_QTY','total')" /> </label> <label>Price: <input type="text" readonly="readonly" name="total" id="total"/> </label> </body> Good day! I am new in javascript function. I have Javascript code for auto calculate here is the code: Code: <script type="text/javascript" language="javascript"> function autocalearn(oText) { if (isNaN(oText.value)) //filter input { alert('Numbers only!'); oText.value = ''; } var field, val, oForm = oText.form, TotEarn = a = 0; for (a; a < arguments.length; ++a) //loop through text elements { field = arguments[a]; val = parseFloat(field.value); //get value if (!isNaN(val)) //number? { TotEarn += val; //accumulate } } var tot=Number(TotEarn) + Number(document.getElementById('Amount').value); oForm.TotEarn.value = tot.toFixed(2); //oForm.TotEarn.value = TotEarn.toFixed(2); //out } </script> <!--Total Deduction AutoCompute--> <script type="text/javascript" language="javascript"> function autocalded(oText) { if (isNaN(oText.value)) //filter input { alert('Numbers only!'); oText.value = ''; } var field, val, oForm = oText.form, TotalDed = a = 0; for (a; a < arguments.length; ++a) //loop through text elements { field = arguments[a]; val = parseFloat(field.value); //get value if (!isNaN(val)) //number? { TotalDed += val; //accumulate } } //oForm.TotalDed.value = TotalDed.toFixed(2); //out var totded=Number(TotalDed) + Number(document.getElementById('Deductions').value); oForm.TotalDed.value = totded.toFixed(2); } </script> and now my problem is...I have a textbox for the overall total, and i want it automatic subtract the total earn and total deduction.. I will attach my codes for further understanding. Thank you in advance Hi.. I have form and i want to input data using barcode and it will display on textbox and after input on the first textbox the focus will go to next textbox untill it will go on the last textbox and on the last textbox it will automatically save the data's on the database. How is it possible? here is my sample code: Code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <html> <head> <script type="text/javascript"> function ini() { // Retrieve the code var code =document.getElementById ("code_read_box1").value; var code =document.getElementById ("code_read_box2").value; var code =document.getElementById ("code_read_box3").value; var code =document.getElementById ("code_read_box4").value; var code =document.getElementById ("code_read_box5").value; var code =document.getElementById ("code_read_box6").value; // Return false to prevent the form to submit return false; } </script> </head> <body onLoad="document.barcode.code_read_box1.focus()"> <form name=barcode onsubmit = "return ini()"> <input type="text" id="code_read_box1" value="" /><br/> <input type="text" id="code_read_box2" value="" /><br/> <input type="text" id="code_read_box3" value="" /><br/> <input type="text" id="code_read_box4" value="" /><br/> <input type="text" id="code_read_box5" value="" /><br/> <input type="text" id="code_read_box6" value="" /><br/> </form> </body> </html> I have a form that is working just fine the only thing is that I need to add a quantity field that will update the price. Can anyone help me with this please. I am not that good at javascript as you can see. I have gotten snippet from here and there to be able to create this form. Here is the code that I have at he moment: Code: <script type="text/javascript"> florida_tax_rate = .07; function update_price(radio) { price = parseFloat(radio.getAttribute("price")); shipping = parseFloat(document.getElementById("shipping").innerHTML); subtotal = document.getElementById("subtotal"); grand_total = document.getElementById("grand_total"); subtotal.innerHTML = price; grand_total.innerHTML = (shipping + price).toFixed(2); update_tax(); } function update_tax() { menu = document.getElementsByName("ShippingState")[0]; state = menu.value; is_florida = state.match(/^(florida|fl)$/i); price = parseFloat(document.getElementById("subtotal").innerHTML); shipping = parseFloat(document.getElementById("shipping").innerHTML); real_subtotal = price + shipping; taxes = 0.00; if (is_florida) { taxes = real_subtotal * florida_tax_rate; } grand_total = document.getElementById("grand_total"); document.getElementById("taxes").innerHTML = taxes.toFixed(2); grand_total.innerHTML = (real_subtotal + taxes).toFixed(2); } </script> <form> <input onchange="update_price(this);" type="radio" name="package" value="non-chamber" price="450.00" /> Non-Chamber Member (Qty: 0-5)<br /> <input name="non-chamber qty" type="text" id="non-chamber qty" value="" size="5" maxlength="999" /> Please Enter Your Quantity <br /> <input onchange="update_price(this);" type="radio" name="package" value="chamber" price="425.00" /> Chamber Member (Qty: 0-5)<br /> <input name="chamber qty" type="text" id="chamber qty" value="" size="5" maxlength="999" /> Please Enter Your Quantity <br /> <input onchange="update_price(this);" type="radio" name="package" value="standard" price="400.00" /> Bulk Orders (Qty: Over 5)<br /> <input name="bulk qty" type="text" id="bulk qty" value="" size="5" maxlength="999" /> Please Enter Your Quantity <br /> <br /><br /> <div style="display:none;"><select onchange="update_tax();" name="ShippingState"> <option value="Florida" selected="selected">Florida</option> </select></div> <br /> Subtotal: $<span id="subtotal">0.00</span><br /> <div style="display:none;">Shipping: $<span id="shipping">0.00</span><br /></div> Taxes: $<span id="taxes">0.00</span><br /> Grand Total: $<span id="grand_total">0.00</span><br /> <br /> <img src="http://www.paypal.com/en_US/i/btn/btn_paynowCC_LG.gif" onClick="document.paypalPayment.submit();" /> <input type="hidden" name="process" id="process" value="1" /> </form> Thanks Hello. I've been teaching myself HTML and CSS for a while, and now I've moved into the world of Javascript (but I'm still very much a beginner). For practice, I've been building a sample sign up form for a mock website, and I'm having problems with the birthdate section. The idea I had was to have MM, DD, and YYYY be the default values of my 3 textboxes (as an example for users), then set the value to nothing when the box gained focus. That all works fine, but I ran into problems when I tried to write an if statement to set the value back to MM, DD, or YYYY if the value was still nothing when the user clicked away. As it is now it just replaces the text inputted into the textbox (which of course is not good). Any ideas for what the problem might be? Code: <form name="signup" action="javascript:void(0);" method="post"> <table> <tr> <td>Date Of Birth:</td> <td> <input name="DOBmonth" type="text" value="MM" size="2" style="color: #555555;" onFocus="clearDOBmonth()" onBlur="restoreDOBmonth()" /> <input name="DOBday" type="text" value="DD" size="2" style="color: #555555;" onFocus="clearDOBday()" /> <input name="DOByear" type="text" value="YYYY" size="4" style="color: #555555;" onFocus="clearDOByear()" /></td> </tr> <tr> <td></td> <td><button name="Submit" type="submit" style="font-size: 1em;">Sign Up</button></td> </tr> </table> </form> <script type="text/javascript" language="javascript"> <!-- document.signup.DOBmonth.value="MM"; document.signup.DOBday.value="DD"; document.signup.DOByear.value="YYYY"; function clearDOBmonth() { document.signup.DOBmonth.value="";} function clearDOBday() { document.signup.DOBday.value="";} function clearDOByear() { document.signup.DOByear.value="";} function restoreDOBmonth() { if ('document.signup.DOBmonth.value = ""') { document.signup.DOBmonth.value = "MM"; // alert(document.signup.DOBmonth.value); } } //--> </script> Another side question, if I set a variable equal to the value of a textbox, then change the value of the variable, does that also change the value of the textbox? or is the variable no longer associated with the textbox. Example: Code: var a = document.form.textbox.value; a = blue; does document.form.textbox.value = blue? or is var a now completely independent of the textbox value? Thanks! I have an online shopping cart and some of the products are sold in boxes of 6. So I am trying to write some code that will alert the customer if they have entered a quantity that isn't some multiple of six. I've tried using the modulus operator as well as dividing by 6 and then checking to see if the result is a whole number but inevitably the alert box pops up no matter what I enter. This is what I'm trying to use now: Code: <head> <script type="text/javascript"> function calculate(qtyordered) { if (qtyordered%6!=0) { alert("Blades are sold in boxes of 6." + '\n' + "Please correct your order quantity."); return false; } else { return true; } } </script> </head> <body> <form action="http://ww4.aitsafe.com/cf/add.cfm" onsubmit="return calculate(qtyordered)" method="post"> <input name="qtyordered" type="text" value="0" size="4" maxlength="4"> </body> What am I doing wrong? Is there a better way to check if the entered quantity is a multiple of 6? 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/ I now have the calculation, topic can be closed! thanks 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, 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") ; 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. 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? 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. 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 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); } |