JavaScript - Issue Getting Function To Calculate A Total
I have created a function but it only half works. I can get the number of contributers to add up but not the total amount of dollars they contributed. I am not sure if my function is wrong or if I am just confused with what variable to output for the dollar amount total. Please assist.
My Function: <script type="text/javascript"> function amountTotal() { total = 0; for (var i=0; i<=amount.length; i++) { total+=amount[i]; } return total; } </script> My output files: <div id=totals> <script type="text/javascript"> document.write("<table border=1' cellspacing=1'>"); document.write("<tr><th id=sumTitle colspan=2'>Summary</th></tr>"); document.write("<tr><th>Contributors</th>"); document.write("<td>"+[i]+"</td>"); document.write("</tr>"); document.write("<tr><th>Amount</th>"); document.write("<td>$ +[total]+</td></tr>"); document.write("</table>"); </script> Similar TutorialsGood 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 am thinking of how to write the code for this: There are 4 textboxes, 3 of which allow you to enter any number (e.g. 1000, 2500, 12345, 100.10, etc.). So whenever I entered a number in one of them (or two or all of them), the 4th read-only textbox will automatically shows the total of the values in the 3 textboxes. So...can anyone give me any references to this? Thanks. I have a small price quote calculator/contact information form. I want the customer to fill out the whole form submit it, and get his/her estimated price based on selections in the form. I am using asp, and I have a javascript for the quote calculations. My question is how would I take this js and execute it when the user hits submit, and then display that quote price on the next page. Here is the javascript that I'm working with: Code: var practice_field = new Array(); practice_field["None"]=0; practice_field["Allergy and Immunology"]=4400; practice_field["Endocrinology"]=4400; practice_field["Pathology"]=4400; practice_field["Dermatology"]=4400; practice_field["Geriatrics"]=4400; practice_field["Physical Rehabilitation"]=4400; practice_field["Family Practice"]=6900; practice_field["General Practice"]=6900; practice_field["Internal Medicine"]=6900; practice_field["Oncology"]=6900; practice_field["Oral Surgery"]=6900; practice_field["Radiology"]=6900; practice_field["Gastroenterology"]=6900; practice_field["Infectious Disease"]=6900; practice_field["Nephrology"]=6900; practice_field["Ophthalmology"]=6900; practice_field["Pediatrics"]=6900; practice_field["Urology"]=6900; practice_field["Anesthesiology"]=9000; practice_field["Cosmetic Surgery"]=9000; practice_field["General Surgery"]=9000; practice_field["Neurology"]=9000; practice_field["Otolaryngology"]=9000; practice_field["Plastic Surgery"]=9000; practice_field["Vascular Surgery"]=9000; practice_field["Cardiology"]=9000; practice_field["Emergency Medicine"]=9000; practice_field["Gynecology"]=9000; practice_field["Orthopedic Surgery"]=9000; practice_field["Pain Management"]=9000; practice_field["Pulmonary Surgery"]=9000; practice_field["Neurological Surgery"]=9900; practice_field["Obstetrics"]=9900; var society_member= new Array(); society_member["None"]=null; society_member["BCMA"]=0.10; society_member["DCMA"]=0.10; society_member["FOGS"]=0.10; society_member["FNS"]=0.10; society_member["PBCMS"]=0.10; society_member["FSPS"]=0.10; function getPracticeField() { var docPracticeField=0; var theForm = document.forms["quoteform"]; var selectedPracticeField = theForm.elements["practice"]; docPracticeField = practice_field[selectedPracticeField.value]; return docPracticeField; } function getSelectedSociety() { var docSelectedSociety=0; var theForm = document.forms["quoteform"]; var selectedSociety = theForm.elements["society"]; docSelectedSociety = society_member[selectedSociety.value]; return docSelectedSociety; } function bareDefensePrice() { var defensePrice=0; var theForm = document.forms["quoteform"]; var includeDefense = theForm.elements["baredefense"]; if(includeDefense.checked==true) { defensePrice=0; } return defensePrice; } function insuranceDefensePrice() { var insuranceDefense=0; var theForm = document.forms["quoteform"]; var includeMoreDefense = theForm.elements["insureddefense"]; if(includeMoreDefense.checked==true){ insuranceDefense=0; } return insuranceDefense; } function calculateTotal() { var defensePrice = getPracticeField() + null - (getPracticeField() * getSelectedSociety()) + bareDefensePrice() + insuranceDefensePrice(); var divobj = document.getElementById('totalPrice'); divobj.style.display='block'; divobj.innerHTML = "Your Pre-Paid Legal Defense Fee Will Be Around $"+defensePrice; } function hideTotal() { var divobj = document.getElementById('totalPrice'); divobj.style.display='none'; } here is the html: Code: <body onload='hideTotal()'> <div id="wrap"> <form action="" id="quoteform" onsubmit=""> <div> <div class="cont_order"> <fieldset> <legend>How Much Will My Pre-Paid Legal Defense Cost?</legend> <label >Choose Your Practice Field</label> <select id="practice" name='practice' onchange="calculateTotal()"> <option value="None">Select Field</option> <option value="Allergy and Immunology">Allergy and Immunology</option> <option value="Endocrinology">Endocrinology</option> <option value="Pathology">Pathology</option> <option value="Dermatology">Dermatology</option> <option value="Geriatrics">Geriatrics</option> <option value="Physical Rehabilitation">Physical Rehabilitation</option> <option value="Family Practice">Family Practice</option> <option value="General Practice">General Practice</option> <option value="Internal Medicine">Internal Medicine</option> <option value="Oncology">Oncology</option> <option value="Oral Surgery">Oral Surgery</option> <option value="Radiology">Radiology</option> <option value="Gastroenterology">Gastroenterology</option> <option value="Infectious Disease">Infectious Disease</option> <option value="Nephrology">Nephrology</option> <option value="Ophthalmology">Ophthalmology</option> <option value="Pediatrics">Pediatrics</option> <option value="Urology">Urology</option> <option value="Anesthesiology">Anesthesiology</option> <option value="Cosmetic Surgery">Cosmetic Surgery</option> <option value="General Surgery">General Surgery</option> <option value="Neurology">Neurology</option> <option value="Otolaryngology">Otolaryngology</option> <option value="Plastic Surgery">Plastic Surgery</option> <option value="Vascular Surgery">Vascular Surgery</option> <option value="Cardiology">Cardiology</option> <option value="Emergency Medicine">Emergency Medicine</option> <option value="Gynecology">Gynecology</option> <option value="Orthopedic Surgery">Orthopedic Surgery</option> <option value="Pain Management">Pain Management</option> <option value="Pulmonary Surgery">Pulmonary Surgery</option> <option value="Neurological Surgery">Neurological Surgery</option> <option value="Obstetrics">Obstetrics</option> </select> <br/> <p> <label >Are You Affiliated With Any of the Following Medical Societies</label> <select id="society" name='society' onchange="calculateTotal()"> <option value="None">Select Society</option> <option value="None">No, I am not</option> <option value="BCMA">Broward County Medical Association</option> <option value="DCMA">Dade County Medical Association</option> <option value="FOGS">Florida Obstetrics & Gynecology Society</option> <option value="FNS">Florida Neurological Society</option> <option value="PBCMS">Palm Beach County Medical Society</option> <option value="FSPS">Florida Society of Plastic Surgeons</option> </select> </p> <br/> <label >What Type of Defense Are You Interested In?</label> <br /> <label for='baredefense' class="inlinelabel">Bare Defense</label> <input type="checkbox" id="baredefense" name='baredefense' onclick="calculateTotal()" /> <br /> <label class="inlinelabel" for='insureddefense'>Insured Defense</label> <input type="checkbox" id="insureddefense" name="insureddefense" onclick="calculateTotal()" /> </p> <div id="totalPrice"></div> </fieldset> </div> <div class="cont_details"> <fieldset> <legend>Contact Details</legend> <label for='name'>Name</label> <input type="text" id="name" name='name' /> <br/> <label for='address'>Address</label> <input type="text" id="address" name='address' /> <br/> <label for='phonenumber'>Phone Number</label> <input type="text" id="phonenumber" name='phonenumber'/> <br/> </fieldset> </div> <input type='submit' id='submit' value='Calculate Rate' onclick="calculateTotal()" /> </div> </form> </div><!--End of wrap--> Hi, please help. I've been trying to check what I did wrong in my code but still the total doesn't show. Below is my javascript function: Code: function CalculateTotal(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r) { var tota= document.getElementById('a'); var totb= document.getElementById('b'); var totc= document.getElementById('c'); var totd= document.getElementById('d'); var tote= document.getElementById('e'); var totf= document.getElementById('f'); var totg= document.getElementById('g'); var toth= document.getElementById('h'); var toti= document.getElementById('i'); var totj= document.getElementById('j'); var totk= document.getElementById('k'); var totl= document.getElementById('l'); var totm= document.getElementById('m'); var totn= document.getElementById('n'); var toto= document.getElementById('o'); var totp= document.getElementById('p'); var totq= document.getElementById('q'); var totr= document.getElementById('r'); var grandTotal = tota + totb +totc + totd + tote + totf + totg + toth + toti +totj + totk + totl + totm + totn + toto + totp +totq + totr; document.getElementById('Total').value = grandTotal.toFixed(2); } Below is my textbox where there are more than 10 textboxes for user to enter donation amount. I'd like to calculate all the donation amount entered then show total in the bottom. Code: <fieldset id="fieldset-in_registration"> <table> <tr> <td style="width:390px;text-align:left"><label for="a" style="font-weight:bold">A. Aloha United Way Community Care Fund </label></td> <td style="float:right"> <input id="a" name="a" class="text" type="text" value="$<?php safeEcho($form['a'])?>" style="width:100px;" onChange="CalculateTotal()" /> <?php helper_error('a');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="b">211 Information and Referral Services </label></td> <td style="float:right"> <input id="b" name="b" class="text" type="text" value="$<?php safeEcho($form['b'])?>" style="width:100px;" onChange="CalculateTotal()" /> <?php helper_error('b');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="c">Volunteer Hawaii/Gifts-in-Kind</label></td> <td style="float:right"> <input id="c" name="c" class="text" type="text" value="$<?php safeEcho($form['c'])?>" style="width:100px;" onChange="CalculateTotal()"/> <?php helper_error('c');?> </td> </tr> </table> </fieldset> <fieldset id="fieldset-in_registration"> <label for="impact" style="font-weight:bold">B. Impact Areas</label> <table> <tr> <td style="width:390px;text-align:left"><label for="d">Crime and Drug Use</label></td> <td style="float:right"> <input id="d" name="d" class="text" type="text" value="$<?php safeEcho($form['d'])?>" style="width:100px;" onChange="CalculateTotal()"/> <?php helper_error('d');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="e">Early Childhood Development</label></td> <td style="float:right"> <input id="e" name="e" class="text" type="text" value="$<?php safeEcho($form['e'])?>" style="width:100px;" onChange="CalculateTotal()" /> <?php helper_error('e');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="f">Emergency and Crisis Services</label></td> <td style="float:right"> <input id="f" name="f" class="text" type="text" value="$<?php safeEcho($form['f'])?>" style="width:100px;" onChange="CalculateTotal()" /> <?php helper_error('f');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="g" >Financial Stability and Independence</label></td> <td style="float:right"> <input id="g" name="g" class="text" type="text" value="$<?php safeEcho($form['g'])?>" style="width:100px;" onChange="CalculateTotal()"/> <?php helper_error('g');?> </td> </tr> <tr> <td style="width:390px;text-align:left"><label for="h" >Homelessness</label></td> <td style="float:right"> <input id="h" name="h" class="text" type="text" value="$<?php safeEcho($form['h'])?>" style="width:100px;" onChange="CalculateTotal()"/> <?php helper_error('h');?> </td> </tr> </table> </fieldset> <fieldset id="fieldset-in_registration"> <p>D. <b>Agency/Program Support ($48 MINIMUM PER CHOICE)</b></p> <p>My gift is designated to one or more specific agencies or programs. Processing fee may apply. <p style="color:#FF0000">(Note: Agency Name is intentionally shorten/cut-off and indented to the next line to fit in the page. Choose either one of the indented line will give the same code.)</p> <div class="formfield"> <table> <tr> <td> <select id="designation_list1" name="designation_list1" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="i" name="i" class="text" type="text" value="$<?php safeEcho($form['i'])?>" style="width:100px;" onChange="CalculateTotal()""/> </td> </tr> <tr> <td> <select id="designation_list2" name="designation_list2" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="j" name="j" class="text" type="text" value="$<?php safeEcho($form['j'])?>" style="width:100px;" onChange="CalculateTotal();"/> </td> </tr> <tr> <td> <select id="designation_list3" name="designation_list3" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="k" name="k" class="text" type="text" value="$<?php safeEcho($form['k'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list4" name="designation_list4" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="l" name="l" class="text" type="text" value="$<?php safeEcho ($form['l'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list5" name="designation_list5" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="m" name="m" class="text" type="text" value="$<?php safeEcho($form['m'])?>" style="width:100px;" onChange="CalculateTotal();"/> </td> </tr> <tr> <td> <select id="designation_list6" name="designation_list6" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="n" name="n" class="text" type="text" value="$<?php safeEcho($form['n'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list7" name="designation_list7" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="o" name="o" class="text" type="text" value="$<?php safeEcho($form['o'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list8" name="designation_list8" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="p" name="p" class="text" type="text" value="$<?php safeEcho($form['p'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list9" name="designation_list9" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="q" name="q" class="text" type="text" value="$<?php safeEcho($form['q'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td> <select id="designation_list10" name="designation_list10" size="1" style="overflow-x:scroll; width:390px; "> <?php foreach ($designation_list as $descode => $prompt) : ?> <option value="<?php echo $descode; ?>" ><?php safeEcho($descode); ?> </option> <?php endforeach; ?> </select> </td> <td> <input id="r" name="r" class="text" type="text" value="$<?php safeEcho($form['r'])?>" style="width:100px;" onChange="CalculateTotal()"/> </td> </tr> <tr> <td style="text-align:right;"><b>TOTAL GIFT(S) DESIGNATED (A-D)</b><BR /> (Must not exceed donation amount)</td> <td><input name="Total" id="Total" type="text" maxlength="10" readonly="true" onChange="CalculateTotal(this.value)" /></td> </tr> </table> Please help. I tried for how many days using the javascript calculations and still didn't work. I have a form with the same calculations and it does work but this one doesn't. Please help. Thanks a lot. Hope to hear from you soon. Need help please asap. It might be simple but i couldn't work out the script. help! ---------------- Formfield.anzahl1 = number entered by customer Formfield.Price1 = Ergebnisfeld1 e.g. Anzahl1= 1 Price = 270 *if Anzahl1 = 2 then Price = 270*2 I need to do this for two form option. 2nd field would be as follows Formfield.Anzahl2= number entered by customer Formfield.Price2 = Ergebnisfeld2 Then Formfield.Total = Ergebnisfeld1 + Ergebnisfeld2 ------------------- How can I convert these above to javascript? Hi, I'm trying to add the total number of costs depending on the rows added to return the subtotal then later add the service charge which gives the total grand amount. I also need to add the item number when a new row is added. Can any1 help? Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>untitled</title> <script type="text/javascript"> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var colCount = table.rows[0].cells.length; for(var i=0; i<colCount; i++) { var newcell = row.insertCell(i); newcell.innerHTML = table.rows[0].cells[i].innerHTML; //alert(newcell.childNodes); switch(newcell.childNodes[0].type) { case "text": newcell.childNodes[0].value = ""; break; case "checkbox": newcell.childNodes[0].checked = false; break; case "select-one": newcell.childNodes[0].selectedIndex = 0; break; } } } function deleteRow(tableID) { try { var table = document.getElementById(tableID); 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) { if(rowCount <= 1) { alert("Cannot delete all the rows."); break; } table.deleteRow(i); rowCount--; i--; } } }catch(e) { alert(e); } } </script> </head> <body > <form action="#" id="calcForm" method="post"> <table border="0" width="680" cellpadding="0" cellspacing="0"> <tr> <td width="60" align="left" valign="top"><b>Item No</b></td> <td width="3"> </td> <td width="290" align="left" valign="top"><b>Description</b></td> <td width="3"> </td> <td width="210" align="left" valign="top"><b>Part No.</b></td> <td width="3"> </td> <td width="50" align="left" valign="top"><b>QTY</b></td> <td width="3"> </td> <td width="63" align="left" valign="top"><b>Cost</b></td> </tr> </table> <table id="parts" border="0" width="680" cellpadding="0" cellspacing="0"> <tr> <td width="60" align="left" valign="top"><INPUT type="checkbox" name="chk"/> <b>1</b></td> <td width="3"> </td> <td width="290" align="left" valign="top"> <input type="text" name="partdesc[]" size="40" value="<?=$info['partdesc'][$x]?>"> </td> <td width="3"> </td> <td width="210" align="left" valign="top"> <input type="text" name="partno[]" size="30" value="<?=$info['partno'][$x]?>"> </td> <td width="3"> </td> <td width="50" align="left" valign="top"> <input type="text" name="qty[]" size="2" value="<?=$info['qty'][$x]?>"> </td> <td width="3"> </td> <td width="63" align="left" valign="top"> <input type="text" name="cost[]" size="4" value="<?=$info['cost'][$x]?>"> </td> </tr> </table> <table id="parts" border="0" width="680" cellpadding="0" cellspacing="0"> <tr> <td width="60" align="left" valign="top"> </td> <td width="3"> </td> <td width="290" align="left" valign="top"> </td> <td width="3"> </td> <td width="210" align="left" valign="top"><b>Sub Total</b></td> <td width="3"> </td> <td width="50" align="left" valign="top"> </td> <td width="3"> </td> <td width="63" align="left" valign="top"> <input type="text" name="subtotal" size="4" value="<?=$info['subtotal']?>"> </td> </tr> <tr> <td width="60" align="left" valign="top"> </td> <td width="3"> </td> <td width="290" align="left" valign="top"><INPUT type="button" value="Add Row" onclick="addRow('parts')" /><INPUT type="button" value="Delete Row" onclick="deleteRow('parts')" /></td> <td width="3"> </td> <td width="210" align="left" valign="top"><b>Service Charge</b></td> <td width="3"> </td> <td width="50" align="left" valign="top"> </td> <td width="3"> </td> <td width="63" align="left" valign="top"> <input type="text" name="charge" size="4" value="<?=$info['charge']?>"> </td> </tr> <tr> <td width="60" align="left" valign="top"> </td> <td width="3"> </td> <td width="290" align="left" valign="top"> </td> <td width="3"> </td> <td width="210" align="left" valign="top"><b>Grand Total</b></td> <td width="3"> </td> <td width="50" align="left" valign="top"> </td> <td width="3"> </td> <td width="63" align="left" valign="top"> <input type="text" name="gtotal" size="4" value="<?=$info['gtotal']?>"> </td> </tr> </table> </form> </body> </html> Hi everyone, I am pretty new to JS and I am looking for help writing a function that will dynamically calculate filed values. I have a PHP-generated form which may have a varying number of fields. I need to: 1. calculate the line total for each row -- unitprice * units = linetotal 2. calculate total of all linetotals. I have named my fields as follows: unitprice[1], unitprice[2]... , units[1], units[2], ... I have the following calculate function: Code: function calculateOld() { // get both values unitprice = document.forms["invoice"].unitprice.value; units = document.forms["invoice"].units.value; // do some calculation lineTotal = formatNumber((unitprice * units), 2); // set the value in the right field document.forms["invoice"].linetotal.value = lineTotal; unitprice2 = document.forms["invoice"].unitprice2.value; units2 = document.forms["invoice"].units2.value; if(unitprice2 != '') { // do some calculation lineTotal2 = formatNumber((unitprice2 * units2), 2); // set the value in the right field document.forms["invoice"].linetotal2.value = lineTotal2; document.forms["invoice"].totalprice.value = formatNumber((parseFloat(lineTotal) + parseFloat(lineTotal2)),2); } else { document.forms["invoice"].linetotal2.value = ''; document.forms["invoice"].totalprice.value = formatNumber(lineTotal,2); } } This does calculate what I need but only if I have up to two rows. I need to make the function dynamically count how many rows there are, and calculate the linetotal for each row. And here's where my limited JS knowledge brings me to a halt. I have been thinking about what this new and dynamic function should look like, but that's the best I could produce... Code: function calculate() { var unitprice[i] = document.forms["invoice"].unitprice[i].value; var units[i] = document.forms["invoice"].units[i].value; var linetotal[i] = formatNumber((unitprice[i] * units[i]), 2); return linetotal; } Your help will be appreciated. Please explain how things are done, don't just give me the code. Thanks in advance! <script> function calculateamt() { //var ckdp122 = parseFloat(document.getElementById('ckdp').value,2); var ty = parseFloat(document.getElementById('t1').value,2); var zx = parseFloat(document.getElementById('t3').value,2); var zy = parseFloat(document.getElementById('t2').value,2); var zz = parseFloat(document.getElementById('t4').value,2); //var zz = parseFloat(document.getElementById('t3').value,2); //var eey=(((ty)-(zz))/(ty))*100; //var deey=eey.toFixed(2); var qq=(ty)*(zx); var rr=(zy)*(zz); //document.getElementById('diffob').value=deey; var r=(qq)+(rr); document.getElementById('ta').value=r; } function calculateamt1() { //var ckdp122 = parseFloat(document.getElementById('ckdp').value,2); var ty1 = parseFloat(document.getElementById('t11').value,2); var zx1 = parseFloat(document.getElementById('t15').value,2); var zy1 = parseFloat(document.getElementById('t12').value,2); var zz1 = parseFloat(document.getElementById('t14').value,2); //var zz = parseFloat(document.getElementById('t3').value,2); //var eey=(((ty)-(zz))/(ty))*100; //var deey=eey.toFixed(2); var qq=(ty1)*(zx1); var rr=(zy1)*(zz1); //document.getElementById('diffob').value=deey; var r1=(qq)+(rr); document.getElementById('tb').value=r1; } </script> <body> <p> </p> <form id="form1" name="form1" method="post" action=""> <table width="688" height="64" border="1"> <tr> <td width="62">Fork</td> <td width="146"><label> <input type="text" name="t1" id="t1" /> </label></td> <td width="146"><label> <input type="text" name="t3" id="t3" /> </label></td> <td width="140"><label></label></td> <td width="160"><label> <input type="text" name="ta" id="ta" /> </label></td> </tr> <tr> <td> </td> <td><label> <input type="text" name="t2" id="t2" /> </label></td> <td><label> <input type="text" name="t4" id="t4" onkeyup="calculateamt()" /> </label></td> <td> </td> <td><label> <input type="text" name="textfield6" id="textfield6" /> </label></td> </tr> <tr> <td width="62">Brake</td> <td width="146"><label> <input type="text" name="t11" id="t11" /> </label></td> <td width="146"><label> <input type="text" name="t15" id="t15" /> </label></td> <td width="140"><label></label></td> <td width="160"><label> <input type="text" name="tb" id="tb" onkeyup="calculateamt1()" /> </label></td> </tr> <tr> <td> </td> <td><label> <input type="text" name="t12" id="t12" /> </label></td> <td><label> <input type="text" name="t14" id="t14" /> </label></td> <td> </td> <td><label> <input type="text" name="textfield6" id="textfield6" /> </label></td> </tr> </table> </form> i have written 2 functions for the above ta and tb calculations but tb and tb are same calculations so what i want to do is only one funcntion to calculate both values plz help me to do this using one function plzzzzzzzzzzzz help me I am trying to create a function to calculate windchill using the windchill equation. Code: 35.74 + 0.6215T - 35.75V (**0.16) + 0.4275TV(**0.16) I have already validated the fields and they are working but for the life of me I can not create a function to calculate the windchill using the above windchill equation. Here is what I do have Code: function Calc(myform) { var tempAmount=document.Chill.OutdoorTemp.value var tempAmount=parseInt(tempAmount,10) if (isNaN(tempAmount) || (tempAmount<=0)) { alert ("The temperature is not a valid number!") document.Chill.OutdoorTemp.value=" " document.Chill.OutdoorTemp.focus() } else { var speed=document.Chill.windSpeed.value var speed=parseFloat(speed) if (isNaN(speed) || (speed<=0)) { alert("The wind speed is not a valid number!") document.Chill.windSpeed.value=" " document.Chill.windSpeed.focus() } } } Any help would be greatly appreciated thanks. I need some help on my math equation, I got the calculations and confirm.submit, and the alert messages to all work properly, but when I go to put the data into the math equation, I am coming up with some outrageous number way off from what it is supposed to be. What I am trying to accomplish is to take the calculated number of day and hours and minutes; multiply the total time in hours by the equipment cost per hour and calculate the total amount of rent. My problem I think is in the calculate total amount of rent section in the script. Please help, your expertise is greatly appreciated. Below is the math equation in the script section: Code: //calculate days from date field function checkit() { var today = new Date(); var nowyear = today.getFullYear(); var d1 = document.forms[0].pickupDate.value.split("/"); var yr = d1[2]; var mm = d1[0]-1; var dy = d1[1]; var OK1 = checkValidDate(yr,mm,dy); if ((yr < nowyear || yr > nowyear +1)) {OK1 = false} // only valid for current year and next year var d2 = document.forms[0].returnDate.value.split("/"); yr = d2[2]; mm = d2[0]-1; dy = d2[1]; var OK2 = checkValidDate(yr,mm,dy); if ((yr < nowyear || yr > nowyear+2)) {OK2 = false} if ((!OK1) || (!OK2)) { alert ("Invalid dates\(s\) or incorrect format! Please try again."); document.forms[0].pickupDate.value = ""; document.forms[0].returnDate.value = ""; return false; } // arbitrary or example start and end times obtained from elsewhere (select lists) var fhrs = parseFloat(document.forms[0].pickupHours.value); var fmins = parseFloat(document.forms[0].pickupMinutes.value); var shrs = parseFloat(document.forms[0].returnHours.value); var smins = parseFloat(document.forms[0].returnMinutes.value); var firstDate = new Date(d1[2],d1[0]-1,d1[1],fhrs,fmins); // note month must be 0-11!! Also note USA date format var secondDate = new Date(d2[2],d2[0]-1,d2[1],shrs,smins); var difference = secondDate.getTime() - firstDate.getTime(); var secs = difference/1000; var days = Math.floor(secs/86400); secs %= 86400; var hours= Math.floor(secs/3600); if (hours<10) {hours = "0" + hours} secs %= 3600; var mins = Math.floor(secs/60); if (mins<10) {mins = "0" + mins} alert ("Time Difference is " + days + " Days " + hours + " Hours " + mins + " Minutes"); //calculate total amount of rent var equip = parseFloat(document.forms[0].equipment.value); var total = (((days * 24) + hours + mins) * 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} } function checkValidDate(yr,mm,dy) { var nd = new Date(); nd.setFullYear(yr,mm,dy); // YYYY,MM(0-11),DD var ndmm = nd.getMonth(); if (ndmm != mm) { return false; } else { return true; } } This is the form in the body section: Code: <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" id = "date1" 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" id = "date2" 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" onblur="checkAge(this.value)" /> </td> </tr> <tr> <td colspan = "3" align = "center"> <input type = "submit" name = "submit" value = "Submit Reservation" onclick = "return checkit()"/> <input type = "button" value = 'Set Cookies' onclick = "setCookie('anyName', cookieValue ,expDate)"> <input type = "button" value = 'Display Cookies' onclick = "dispCookie('anyName')"> </td> </tr> </table> </form> I am trying to create a simple auto-calculate function for a webpage. What should be happening: The 'onchange' command should pass the 'price' of the item to the function, the function should then cycle through all the dropdowns (or checkboxes or fields) and calculate the total. What is happening: It is only picking up the last checkbox. It seems that the 'for' loop only remembers the last item in the array. What am I doing wrong? How can I get the code to remember all the items? thanks, Code: <script language="JavaScript" type="text/javascript"> function calculateTotal(price) { var total = 0; var cList = ['sel1','sel2','sel3']; for (i=0;i<2;i++); var select = GetE(cList[i]); total+= price * (select.options[select.selectedIndex].value); GetE("totalShow").innerHTML = total.toFixed(2); } function GetE(id) {return document.getElementById(id); } </script> <html> <head></head><body> <form id="form1" name="form1" method="post" action=""> <select name="sel1" id="sel1" onchange="calculateTotal(100)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel2" id="sel2" onchange="calculateTotal(200)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> <select name="sel3" id="sel3" onchange="calculateTotal(300)"> <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select><br><br> </form> <br>total <span id="totalShow">0.00</span> </body></html> Good morning Guru's and Experts, I really need your help with this one. It seems that the function this_week('end') is returning a bad date of 12/33/2014 (mm/dd/yyyy) where it should properly read: 01/02/2015 Code: function this_week(x) { var today, todayNumber, fridayNumber, sundayNumber, monday, friday; today = new Date(); todayNumber = today.getDay(); mondayNumber = 1 - todayNumber; fridayNumber = 5 - todayNumber; if (x === 'start') { //var start_dd = today.getDate() + mondayNumber var start_dd = today.getDate() var start_mm = today.getMonth() + 1 var start_yyyy = today.getFullYear() return start_mm + '/' + start_dd + '/' + start_yyyy } if (x === 'end') { var end_dd = today.getDate() + fridayNumber var end_mm = today.getMonth() + 1 var end_yyyy = today.getFullYear() return end_mm + '/' + end_dd + '/' + end_yyyy } } Reply With Quote 12-29-2014, 07:43 PM #2 Philip M View Profile View Forum Posts Supreme Master coder! Join Date Jun 2002 Location London, England Posts 18,371 Thanks 204 Thanked 2,573 Times in 2,551 Posts I understand that you are trying to get the date next Friday. Try this script:- Code: <span id = "info"></span> <script type = "text/javascript"> var curr = new Date(); // get current date var first = curr.getUTCDate() - curr.getUTCDay(); // First day is the day of the month - the day of the week var last = first + 5; // last day is the first day + 5 = Friday var lastday = new Date(curr.setDate(last)); var yy = lastday.getUTCFullYear(); var mth = lastday.getUTCMonth()+1; if (mth<10) {mth = "0" + mth} var dy = lastday.getUTCDate(); if (dy<10) {dy = "0" + dy} // now manipulate the display of year,month,date as desired var result = mth + "/" + dy + "/" + yy; document.getElementById("info").innerHTML = "Week Ending Friday " + result; </script> Lottery: A tax on people who are bad at math. I've been messing with this code for about a couple of hours, and I did everything down to the wire..yet still I am unable to get it to work. When I input the numbers, and click off to the side nothing appears down at the final textarea of the form which is suppose to show the average. I've tried just about everything, sadly all I have to go by is other example codes, and the very intricate instructions which states I must pass the values to the calcAvg() to the second function of performCalc(), which I did, and then I assigned the var calcResult another value. From there I did the return..and after that I'm rather loss as to what to do next to get this code to work, any tips? Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//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" /> <title>Calculation Average</title> <script type="text/html"> /* <![CDATA[ */ function calcAvg() { var calcResult=document.numbers.number1.value + document.numbers.number2.value +document.numbers.number3.value + document.numbers.number4.value + document.numbers.number5.value } function performCalc() { var calcResult = calcResult / 5 return calcResult; } /* This is what I got so far, as you can see I need plenty of help!*/ </script> </head> <H1> Calculate Average of Numbers</H1> <body> <form action="" name="numbers"> <table> <tr> <td> <tr> <td>Enter the five numbers:<br /> </td></tr> <tr><td> <input type="text" name="number1" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number2" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number3" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number4" size="3" onchange="calcAvg()" text="0" /></td> </tr> <tr> <td> <input type="text" name="number5" size="3" onchange="calcAvg()" text="0" /></td> </tr> </table> </form> <form action="" name="averageResult"> <p> Estimate average: <input type="text" name="average" size="5" style="border-style: none; border-color: inherit; border-width: medium; background-color: Transparent" text="0" /></p> </form> </body> </html> Good day everyone. I have a challenge with a function that works in Firefox, but not IE, Chrome or Safari. We've been building a site with a mix of Javascript and PHP using Google Maps. Another developer began the project and left a large mess which we're cleaning up. Even though it's under development, it can be viewed at www.recareas.com/demo The challenge we have is this . . . When the site home page, which is a large map, loads, it displays the US with state markers. The user will then select a state, for example, Colorado. The map then zooms in and displays markers for that state. Ultimately we won't be showing markers at the point until the visitor selects an activity from a menu. When the visitor clicks on a location marker, the google call out bubble pops up displaying a list of activities and a More Info button. This more info button when clicked opens a slide out dock on the right side of the screen displaying detailed data about the location selected. The problem we have is that this slide out dock only works in Firefox. It appears that in the other browsers the function that calls the PHP template that builds the right side dock doesn't even load. Can anyone help by giving us some pointers or direction? Here's the function were trying to call from the More Info bubble inside the google map: [code] function locInfo(loc_id) { $.get("includes/z_get_location_details.php", { loc_id: loc_id }, function(data){ $("#infoWindow_location").html(data); $("#r_menu").animate({ width: "500px"}, 200 ); $("#r_menu_left").hide(); $("#r_menu_right").show(); $("#infoWindow").show(); $.getScript("includes/z_get_interests.php?loc_id=" + loc_id); //document.directionsForm.goBtn.disabled=false; }, "html"); } [Icode] Thank you in advance for any help. hey everyone: im using the following function: Code: function getByTag(tagName) { var i, results = [], nodes = document.getElementsByTagName(tagName); for (i = 0; i < nodes.length; i++) { results.push(nodes[i]); } return results; } however when im trying to do this getByTag("div").style.color = "red" nothing happens.any help? Hello, I am trying to make a page with a target heart rate calculator that displays the heart rate in a text box. This code displays on a new page instead of in the box even though I put an input box, plus it doesn't display the correct value. I think the problem is in the function itself: Code: <script> function calcHeartRate() { var age = "" var heartRate = 220 - age var minRate = heartRate * .5 var maxRate = heartRate * .85 rate = document.write(heartRate) document.myForm.yourRate.value = rate } At any rate, here is the form also: Code: <form name = "myForm"> Age:</br> <input type = "text" name = "age" /><br/><br/> <input type = "button" value = "Calculate Your Maximum Heart Rate:" onclick= "calcHeartRate()"/> <br/><br/> Max Heart Rate:<br/> <input type = "text" name = "yourRate" /><br/><br/> </form> I'm sure this is jacked up code since I have definitely been struggling. If you want me to post my entire code, I will, but it is my understanding that it is against the guidelines. Posting a working code is definitely not necessary. Please give me an idea as to what is wrong and I will go from there. I do not want the actual answer. I kind of think the problem is with my age variable but I am not sure what it is. Thanks! Hi all, I'm just starting out with Javascript as a development language and this will probably be a relatively simple problem for someone to solve for me. I am trying to access a variable (this.bodyEl.innerHTML) from within a function but get an error message indicating that it is "undefined". I know that it is a valid variable because I call it elsewhere outside of the inner function itself. I'm sure this is just a scope issue, but I'd welcome any suggestions on how to solve it with an explanation of where I've gone wrong if you have the time. Here's the code: Code: displayFeed: function(responseData) { this.bodyEl.innerHTML = "xxxx"; // I can see this var responseDoc = Presto.Util.parseXml(responseData); var items = Ext.DomQuery.select("/rss/channel/item", responseDoc); items.each(function(item, bodyHTML) { var rssTitle = Ext.DomQuery.selectValue("/title", item); var rssDescription = Ext.DomQuery.selectValue("/description", item); var rssLink = Ext.DomQuery.selectValue("/link", item); // but this results in an undefined error this.bodyEl.innerHTML = '<a href="' + rssLink + '">' + rssTitle + '</a><br/>'; }); // end of items processing } This is a fragment of the code from my script. The first access of "this.bodyEl.innerHTML" works fine, but the second access in the items.each loop doesn't and I get an undefined variable error. Is this a scoping problem, and if so how is it best solved. Thanks in advance, Innes (NZ) Hi, I'm trying to call a Js function from a test.js located in a HTML file. I'm getting error message "Object has no method..." in Chrome. But no issues are seen in Firefox. Can any one please let me know how i can fix this. <html> <head> .... .... .... <div> <html> <head> <script src="test.js"></script> <script> function aFunc() { alert ("Inside aFunc"); } </script> </head> <body> </html> .... .... .... </div> </head> </html> test.js function bFunc () { aFunc (); } |