JavaScript - Simple Math Calculation
Hi. I am new to javascript programming so please go easy on me. I am creating a site for a flooring store and need to include a price calculator/estimator.
What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and th tird being selected from the pulldown. Can someone please educate me on how to do this? Similar TutorialsI'm a student learning javascript, I'm having a very basic problem. I have to write a script that outputs XHTML text that keeps displaying in the browser window that multiples of the integer 2, namely 2, 4, 8, 16, 32, 64, etc. This is the code i have, Code: <!-- var product=2; while { product =2*product; } document.writeln( +product+ ); // --> And it pretty much does nothing. Help would be much appreciated Dave Ok I am looking for a simple bmi calculator that calculates body mass index then in a seperate table calculates what a target weight should be based on the goal bmi. no need for making it look fancy, just functionality for now. thanks!
Hi. I am new to javascript programming so please go easy on me. I am creating a website for a flooring store and need to include a price calculator/estimator. What I need to do is allow the visitor to input the room size (length x width) and choose a flooring material from a pulldown list, and receive a price. The pulldown list would have flooring materials such as carpet, tile, wood, etc and each of these would have a fixed dollar amount associated with them (which would be hidden). So basically it is just a script that would multiply 3 numbers, with two of the numbers being input by the visitor, and the third being selected from the pulldown. Can this be done with Javascript, and can someone please educate me on how to do this? I am at a lost, new to JavaScript and not sure why I am getting Nan Code: <script type="text/javascript"> var num1; var num2; var num3; var ave_num=Math.round((num1 + num2 + num3) / 3); //follow prompts to enter numbers and print average </script> I've designed a snippet of javascript to receive numbers, add them together, and then display the total. What i'd like to do now is display the amount of numbers added together "count", and then average them all together. Problem is, the count just won't display, so i'm uncertain if I have a logic error in my code or just an html issue? I'd really appreciate the help! Code: <html> <head> <script type="text/javascript"> var count = 0; var total = 0; var number = 0; function AverageNumbers(form) { number = document.getElementById('num1').value; count++; total = parseInt(number) + parseInt(total); average = parseInt(number) + parseInt(count) if (number!=null && number!="") { document.getElementById('total').innerHTML = total; document.getElementById('count').innerHTML = count; } return count; return total; } </script> </head> <body> <form> <INPUT TYPE="number" NAME="inputbox" ID="num1"> <INPUT TYPE="button" NAME="button" Value="Click" onClick="AverageNumbers(this.form)"> </form> <div id="total"><div> <br> </br> <div id="count"><div> </body> </html> I'm making a 3d pie chart. I have the points and the correct method to fill everything but when the slice rotates I want to make the outer edge filled, but in order to do that I have to figure out what math I use to find the leading edge. I made a picture to hopefully explin what I need to find. I figure it might be the tangent but I was hoping someone smarter than I could send me in the right direction. I just need someone to help me pinpoint my next step. Right now the rendering uses start and end angles to first make the top and bottom sections, fills them and then it makes an arc along the top of the slice from start to end then from end to start on the bottom slice and completes the polygon by going back the first point in the arc. I need to make two separate polygons if the end or start are further from the center than the( tangent?) point. Need some advice. Hope someone has an idea. I'm new to programming and can't figure out why this won't work: Code: print " var 1A == Math.sqrt(Math.pow(B,2) - Math.pow(C,2)); \n"; print " var 1B == Math.sqrt(Math.pow(A,2) + Math.pow((F + G),2)); \n"; print " var 1C == B + D; \n"; print " var 1D == C - B; \n"; print " var 1E == E; \n"; print " var 1F == (Math.sqrt(Math.pow(C,2) - Math.pow(A,2)) - G); \n"; print " var 1G == (Math.sqrt(Math.pow(C,2) + Math.pow(A,2)) - F); \n"; print " var 1H == ((F + G) / B); \n"; I have tried debugging it using Firebug and I get this error: Quote: identifier starts immediately after numeric literal I get the error on the line with var 1A, but I'm pretty sure that 1B, 1F, and 1G would all have the same error. Thanks for the help in advance guys! BTW the reason why the code is being printed is because I'm programming with Perl and running on a webpage using html and javascript. I can't wrap my head around this at the moment so with the hope of finding someone willing to take a stab I am posting this to all of you. I need to create a savings ticker that shows $ saved per second. The data is as follows then = date script is created now = current date std = savings to date in $ avg = average savings per second in $ It would need to calculate the difference in time between then and now, convert that to an integer that can then be multiplied by avg then std would be added. thanks in advance Either I made an uh-oh, or there is a serious problem with Javscripts math functions. Math.sin(x) returns the sine of x in radians. Last time I checked, the sine of pi radians is 0, but in javascript: Code: Math.sin(Math.PI) // returns 1.2246467991473532e-16 Any idea why? Julian Just started to learn java & came up with the following, but can't get the math.round to work. Anyone able to tell me where I'm going wrong please ??? <p> <script type="text/javascript">// <![CDATA[ var metrics = { "mm" : 1, "cm" : 10, "m" : 1000, "inch" : 25.4, "foot" : 304.8 }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) } function roundme(len, wid, sq){ math.round.len; wid = math.round(wid); sq = math.round(sq); alert(len); }; function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) }; function changeme(id, action) { var val = document.getElementById("sizegroup"); if (val.style.display == 'none') { val.style.display = 'block' } else { val.style.display = 'none' } }; function convert(num, dec){ var val = document.getElementById("boxa").value; var val2 = document.getElementById("boxb").value; if(isNaN(val)){return val}; if(isNaN(val2)){return val2}; document.getElementById("boxc").value = val * metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; metrics[document.getElementById("choice1").value]/ metrics[document.getElementById("choice3").value]; document.getElementById("boxd").value = val2 * metrics[document.getElementById("choice2").value]/ metrics[document.getElementById("choice4").value]; document.getElementById("sqmtrs").value = document.getElementById("boxc").value * document.getElementById("boxd").value ; document.getElementById("boxc").value = math.round(document.getElementById("boxc").value); }; var interval = null; function watchChanges(){ interval == null ? setInterval("convert()", 500) : clearInterval(interval); } // ]]></script> </p> <p>Length in imperial-metric / Width in imperial-metric</p> <div><input id="boxa" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice1" onchange="convert();"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxb" style="width: 40px;" onfocus="watchChanges()" onblur="watchChanges()" type="text" /><select id="choice2" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option value="m">metres</option> <option selected="selected" value="foot">feet</option> <option value="inch">inches</option> </select></div> <div><input id="boxc" style="width: 40px;" type="text" disabled="disabled" /><select id="choice3" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select> <input id="boxd" style="width: 40px;" type="text" disabled="disabled" /><select id="choice4" onchange="convert()"> <option value="mm">millimeters</option> <option value="cm">centimeters</option> <option selected="selected" value="m">metres</option> <option value="foot">feet</option> <option value="inch">inches</option> </select></div> <p> </p> <div>Total sq metres : <input id="sqmtrs" style="width: 40px;" type="text" value="" disabled="disabled" /></div> <p> </p> <div class="label">Please round up to half a metre when choosing</div> <table border="0" cellspacing="0" cellpadding="5"> <tbody> <tr> <td>Round:</td> <td><input type="text" name="numberfield" value="" /> to <input type="text" name="decimalfield" value="2" size="3" /> decimal places</td> </tr> <tr> <td>Result:</td> <td><input type="text" name="roundedfield" value="" /> <input onclick="roundNumber(numberfield.value, decimalfield.value);" type="button" value="Calculate" /></td> </tr> </tbody> </table> How can you add/substract two numbers in javascript if they are written out as words such as one|two|three|four|five|six|seven|eight|nine|ten. Code: if ((word[0].match(/one|two|three|4|five|six|seven|eight|nine|ten/)) && (word[1].match(/plus|add/)) && (word[2].match(/one|two|three|4|five|six|seven|eight|nine|ten/))) { document.result.result.value = "The answer is ?"; return true;} hey. im working on a facebook app.. this is what i got so far. PHP Code: <script language="JavaScript"> <!-- var theImages = new Array() theImages[0] = "http://img688.imageshack.us/img688/4787/logo1tq.jpg" theImages[1] = "http://img641.imageshack.us/img641/8292/logo2yex.jpg" theImages[2] = "http://img864.imageshack.us/img864/4097/logo3ik.jpg" theImages[3] = "http://img543.imageshack.us/img543/9046/logo4pu.jpg" theImages[4] = "http://img21.imageshack.us/img21/2567/logo5q.jpg" theImages[5] = "http://img842.imageshack.us/img842/696/logo6o.jpg" theImages[6] = "http://img85.imageshack.us/img85/7831/logo7k.jpg" var j = 0 var p = theImages.length; var preBuffer = new Array() for (i = 0; i < p; i++){ preBuffer[i] = new Image() preBuffer[i].src = theImages[i] } var whichImage = Math.round(Math.random()*(p-1)); function showImage(){ document.write('<img src="'+theImages[whichImage]+'">'); } //--> </script> <script language="JavaScript"> <!-- showImage(); //--> </script> now i want that the app posts the random image automaticlly to the useres timeline.. for example: if the random image is theImages [3] then it should post the image theimage [3] to the users timeline.. i see alot of facebook apps doing this.. thanks in advance I've started studying JavaScript recently. The following simple scenario from the Russian textbook cannot be implemented on my PC. Code: <HTML> <HEAD> <TITLE>Object Math Example</TITLE> </HEAD> <BODY> <h1>Object Math Example</h1> <p>Насколько случайны числа, полученные генератором случайных чисел? Подсчитаем среднее 5000 случайных чисел.</p> <SCRIPT LANGUAGE="JavaScript"> total = 0; for (i = 0; i<5000; i++) { num = Math.random(); total += num; document.status = "Generated " + i + " numbers"; } average = total / 5000; average = Math.round(average * 1000 / 1000); document.write("<h2>" arithmetic mean of random numbers + average + "</h2>"); </SCRIPT> </BODY> </HTML> I just typed the script char by char. I use Firefox browser, v.3.5.7. The error console does not display any mistakes. Please, explain me what is wrong in the code. The problem that I am facing is my total amount comes out to $102.46 through my calculations on the page. But when it is moved over to PayPal, the value becomes $102.44. I have many more amount that are also either up .2 cents or down .2 cents. I managed to track this down as a rounding issue. Anytime I do the math, it rounds the amount off and gives the total. But since quantity is involved which is done through PayPal, I had to divide my total by the quantity to bring it back to its original amount thus allowing PayPal to multiply the amount by the quantity. I've pulled my hair out on this one. Ay help would be appreciated. Thank you Code: <html> <head> <title>TESTING</title> <script src="SpryAssets/SpryValidationSelect.js" type="text/javascript"></script> <script src="SpryAssets/SpryValidationCheckbox.js" type="text/javascript"></script> <script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script> <link href="SpryAssets/SpryValidationSelect.css" rel="stylesheet" type="text/css"> <link href="SpryAssets/SpryValidationCheckbox.css" rel="stylesheet" type="text/css"> <link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css"> </head> <td width="95%" align="center" class="TextoImageSpace"><table border="0" cellpadding="0" cellspacing="0" class="TextoImageSpace_center"> <tr> <td align="center"><h2>Pricing</h2> <form action="https://www.paypal.com/cgi-bin/webscr" method="post" name="price" id="price"> <p>Select amount please.</p> <p> <input type="hidden" name="cmd" value="_xclick" /> State: <br /> <span id="spryselect1"> <!-- selects the state // onclick changes the variables specified values --> <select name="combo0" id="combo_0" onclick="roundNumber(amount2.value, 2);roundNumberTax(tax.value, 2);roundNumberProduct(product.value, 2);roundNumberShipping(shipping.value, 2);roundNumberAmount(amount2.value, 2)" style="width:200px;"> <option selected="selected"> </option> <option value="70">Arizona</option> </select> <span class="selectRequiredMsg"></span></span><br /> Quantity: <br /> <span id="spryselect2"> <!-- selects the quantity // onclick changes the variables specified values --> <select name="combo1" id="combo_1" onclick="roundNumber(amount2.value, 2);roundNumberTax(tax.value, 2);roundNumberProduct(product.value, 2);roundNumberShipping(shipping.value, 2);roundNumberAmount(amount2.value, 2)" style="width:200px;"> <option selected="selected"> </option> <option value="4">4 - $20.95</option> </select> <span class="selectRequiredMsg"></span></span><br /> Product: <br /> <span id="sprytextfield11"> <label> <input type="text" name="product" id="txt_product" disabled="disabled" value="" style="width:200px;" /> </label> </span><br /> Shipping: <br /> <span id="sprytextfield9"> <label> <input type="text" name="shipping" id="txt_shipping" disabled="disabled" value="" style="width:200px;" /> </label> </span><br /> Taxes: <br /> <span id="sprytextfield10"> <label> <input type="text" name="tax" id="txt_tax" disabled="disabled" value="" style="width:200px;" /> </label> </span><br /> Total: <span id="sprytextfield8"> <input type="hidden" name="amount" id="txt_price" value="" style="width:200px;" /> </span> <input type="hidden" name="amount3" id="txt_price3" value="" style="width:200px;" /> <br /> <span id="sprytextfield7"> <input type="text" name="amount2" id="txt_price2" disabled="disabled" value="" style="width:200px;" /> </span></p> <hr width="100%" /> <p>Please fill in details.</p> <p> <input type="hidden" name="item_name" value="TEST ITEM" /> <input type="hidden" name="button_subtype" value="products" /> <input type="hidden" name="rm" value="1" /> <input type="hidden" name="return" value="http://www.example.com/" /> <input type="hidden" name="cancel_return" value="http://www.example.com/" /> <input type="hidden" name="currency_code" value="USD" /> <input type="hidden" name="bn" value="PP-BuyNowBF:btn_buynowCC_LG.gif:NonHosted" /> <input type="hidden" name="address_override" value="1" /> <input type="hidden" name="shipping" value="0" /> <input type="hidden" name="business" value="wayne@lifelikemedia.ca" /> <input type="hidden" name="quantity" id="quantity" value="1" /> <input type="hidden" name="state" id="state" value="" /> First Name: <br /> <span id="sprytextfield1"> <input type="text" name="first_name" value="TEST" style="width:200px;" /> <span class="textfieldRequiredMsg"></span></span><br /> Last Name: <br /> <span id="sprytextfield2"> <input type="text" name="last_name" value="TEST" style="width:200px;" /> </span> <br /> Address: <br /> <span id="sprytextfield3"> <input type="text" name="address1" value="1234 TEST STREET" style="width:200px;" /> <span class="textfieldRequiredMsg"></span></span><br /> City: <br /> <span id="sprytextfield4"> <input name="city" type="text" value="Scottsdale" style="width:200px;" /> <span class="textfieldRequiredMsg"></span></span><br /> ZIP Code: <br /> <span id="sprytextfield5"> <input type="text" name="zip" value="85260" style="width:200px;" /> </span><br /> Country: <br /> <span id="sprytextfield6"> <input name="country" type="text" disabled="disabled" value="US" style="width:200px;" /> </span><br /> <br /> <span id="sprycheckbox1"> <label> <input type="checkbox" name="replacePolicy" id="replacePolicy" /> </label> <span class="checkboxRequiredMsg">Please read policy.</span></span> <a href="#" class="style10" onClick="window.open('replace.html','popup','width=400,height=300,scrollbars=yes,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,left=50,top=0'); return false">Please read policy.</a><br /> <br /> <input type="image" name="submit" border="0" src="http://www.thinkanddone.com/finance/buynow.jpg" alt="PayPal - The safer, easier way to pay online" /> </p> </form></td> </tr> </table> <script type="text/javascript"> var shipping = document.getElementById("txt_shipping").value; var tax = document.getElementById("txt_tax").value; var product = document.getElementById("txt_product").value; // rounds total amount off function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places var v1 = document.getElementById("combo_1").value, v2 = document.getElementById("combo_0").value; var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); var newnumber2 = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.price.amount2.value = newnumber.toFixed(2); // Output the result to the form field document.price.amount.value = (newnumber2 / v1).toFixed(2); } // rounds tax off function roundNumberTax(rnum, rlength) { // Arguments: number to round, number of decimal places var taxnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.price.tax.value = taxnumber.toFixed(2); // Output the result to the form field } // rounds product off function roundNumberProduct(rnum, rlength) { // Arguments: number to round, number of decimal places var productnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.price.product.value = productnumber.toFixed(2); // Output the result to the form field } // rounds shipping off function roundNumberShipping(rnum, rlength) { // Arguments: number to round, number of decimal places var shippingnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.price.shipping.value = shippingnumber.toFixed(2); // Output the result to the form field } // rounds paypal amount off function roundNumberAmount(rnum, rlength) { // Arguments: number to round, number of decimal places var amountnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength); document.price.amount2.value = amountnumber.toFixed(2); // Output the result to the form field } window.onload = function() { var dropChange = function() { // Declaring variables var v1 = document.getElementById("combo_1").value, v2 = document.getElementById("combo_0").value; var amount3 = document.getElementById("txt_price3").value, amount = document.getElementById("txt_price").value; document.getElementById("txt_price3").value = (amount); document.getElementById("quantity").value = (v1); if (v2 == 70) { document.getElementById("state").value = ("AZ"); } <!-- when state is selected, these calculations are done --> if (v2 == 70) { if (v1 == 4) { document.getElementById("txt_price2").value = v1 * 20.95; document.getElementById("txt_product").value = document.getElementById("txt_price2").value; document.getElementById("txt_price2").value = document.getElementById("txt_product").value * 0.0795; document.getElementById("txt_tax").value = document.getElementById("txt_price2").value; document.getElementById("txt_price2").value = 12; document.getElementById("txt_shipping").value = document.getElementById("txt_price2").value; document.getElementById("txt_price2").value = v1 * 20.95 * 1.0795 + 12.00; } } }; document.getElementById("combo_0").onchange = dropChange; document.getElementById("combo_1").onchange = dropChange; }; </script> <script type="text/javascript"> <!-- var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1", {validateOn:["change"]}); var spryselect2 = new Spry.Widget.ValidationSelect("spryselect2", {validateOn:["change"]}); var sprycheckbox1 = new Spry.Widget.ValidationCheckbox("sprycheckbox1", {validateOn:["change"]}); var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6", "none"); var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5", "zip_code", {validateOn:["change"]}); var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4", "none"); var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3", "none"); var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2", "none"); var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1", "none"); var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7", "none", {validateOn:["change"]}); var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8", "currency", {validateOn:["change"]}); var sprytextfield10 = new Spry.Widget.ValidationTextField("sprytextfield10"); var sprytextfield9 = new Spry.Widget.ValidationTextField("sprytextfield9"); var sprytextfield11 = new Spry.Widget.ValidationTextField("sprytextfield11"); //--> </script> </body> </html> Hi everyone, I am new to Javascript and took a class or 2 in college, but need some help. I need to make a calculation for a webpage that will do the following: Client will insert AWG (wire ) Size, then it will derive the correct Circular Mils that the AWG is equal to from an Access Database ( I assume this is the way to set that up or if I can in Javascript itself, thats fine as well ), then Multiply it by the Number of Strands that the Client will also insert. I had this all set up in Visual Basic and working great, and my boss said he does not want it in a pop up box but prefers it on the website itself hence me reverting to Javascript for this. To visualize it Image 2 boxes with AWG and STRANDS that the client will put in, then another box with TOTAL CMA where the answer will pop up after it has multipled by the AWG individual CMA and number of Strands. I have the general idea to set it up, just do not know how to get the Database in there and Code it properly or whatever. I would appreciate any assistance I can get :-) Thanks everyone. I need help with a javascript calculation. I am a noobie developer as you will probably see by my script but here are my goals: I already have a working bmi calculator for my website where visitor will enter height and current weight to calculate their current bmi. then I want to have a reverse bmi calculator to grab the same height and weight from said bmi calculator to give a calculation with a fillable goal bmi (example: 18-24 "healthy bmi") to read out a goal weight for them to achieve. I have already figured out the first part of the bmi calculation now i just need the second calculation to grab the height and weight from original bmi calculator without needing to be filled in again and compute result in a second table. I will post code that I have come up with so far for the whole page. Thank you in advance for your help! [CODE] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title> HCG Drops Fat Lose 1-2 pounds Per Day! </title> <style type="text/css"> #wrapall { width:1000px; align:center; margin-left: 7em; margin-right: 7em; } #navigationbar{ } #bmibar { width:973px; background-image:url(bmibar2.jpg); background-repeat:no-repeat; background-position:left bottom; padding-bottom:16em; margin:4px; } #Hcgborder { width:973px; background-image:url(index_15.jpg); background-repeat:no-repeat; background-position:left bottom; padding-bottom:17em; } #Hcgborder h3 { width:973px; background-image:url(index_12.jpg); background-repeat:no-repeat; background-position:left top; margin:0px; padding-left:4em; padding-top:8em; } p { background-image:url(index_13.jpg); background-repeat:repeat-y; background-position:left center; margin:0px; padding-left:4em; padding-right:4em; font:family"arial" } #bmiscale{ font-size:14px; padding-left:15px; } #Hcgborder2 { width:973px; background-image:url(index_19.jpg); background-repeat:no-repeat; background-position:left bottom; padding-bottom:0.5em; } #dhtmlgoodies_bmi_calculator{ width:180px; /* Width of entire calculator */ height:145px; /* Height of entire calculator */ font-family: Trebuchet MS, Lucida Sans Unicode, Arial, sans-serif; /* Fonts to use */ } #dhtmlgoodies_bmi_calculator .calculator_form{ /* Form */ width:180px; /* Width of form div */ float:left; /* Position the form at the left of the graph */ padding-left:5px; padding-right:5px; } #dhtmlgoodies_bmi_calculator input{ width:130px; } #dhtmlgoodies_bmi_calculator .calculator_form .textInput{ width:40px; /* Width of small text inputs */ text-align:right; /* Right align input text */ } .barContainer{ /* DIV for both the multicolor bar and users weight bar */ position:absolute; bottom:0px; border:0px solid #4ff; border-bottom:0px; text-align:center; vertical-align:middle; } .barContainer div{ /* colored div inside "barContainer */ border-bottom:1px solid #000; } .barContainer .labelSpan{ /* Label indicating users BMI */ background-color:#FFF; /* White BG */ border:1px solid #000; /* Black border */ padding:1px; /* "Air" inside the box */ font-size:0.9em; /* Font size */ } .clear{ /* Clearing div - you shouldn't do anything with this one */ clear:both; } </style> <script type="text/javascript"> var useCm = false; // Using centimetre for height, false = inch var useKg = false // Using kilos for weight, false = pounds var graphColors = ['#00baff','#02eb07','#ffb400','#ff0000']; var graphLabels = ['']; var labelsPerRow = 1; /* Help labels above graph */ var barHeight = 50; // Total height of bar var barWidth = 50; // Width of bars */ // Don't change anything below this point */ var calculatorObj; var calculatorGraphObj; var bmiArray = [0,18.5,25,30,60]; /* BMI VALUES */ var weightDiv = false; function calculateBMI() { var height = document.bmi_calculator.bmi_height.value; var weight = document.bmi_calculator.bmi_weight.value; height = height.replace(',','.'); weight = weight.replace(',','.'); if(!useKg)weight = weight / 2.2; if(!useCm)height = height * 2.54; if(isNaN(height))return; if(isNaN(weight))return; height = height / 100; var bmi = weight / (height*height); createWeightBar(bmi); } function createWeightBar(inputValue){ if(!weightDiv){ self.status = Math.random(); weightDiv = document.createElement('DIV'); weightDiv.style.width = barWidth + 'px'; weightDiv.className='barContainer'; weightDiv.style.left = Math.round((calculatorGraphObj.offsetWidth/2) + ((calculatorGraphObj.offsetWidth/2) /2) - (barWidth/2)) + 'px'; calculatorGraphObj.appendChild(weightDiv); var span = document.createElement('SPAN'); weightDiv.appendChild(span); var innerSpan = document.createElement('SPAN'); innerSpan.className='labelSpan'; span.appendChild(innerSpan); }else{ span = weightDiv.getElementsByTagName('SPAN')[0]; innerSpan = weightDiv.getElementsByTagName('SPAN')[1]; } var color = graphColors[graphColors.length-1]; for(var no = bmiArray.length-1;no>0;no--){ if(bmiArray[no]>inputValue)weightDiv.style.backgroundColor = graphColors[no-1]; } if(inputValue/1>1){ innerSpan.innerHTML = inputValue.toFixed(2); span.style.display='inline'; }else span.style.display='none'; var height = Math.min(Math.round(barHeight * (inputValue / bmiArray[bmiArray.length-1])),barHeight-10); span.style.lineHeight = Math.round(height) + 'px'; weightDiv.style.height = height + 'px'; } function validateField() { this.value = this.value.replace(/[^0-9,\.]/g,''); } function initBmiCalculator() { calculatorObj = document.getElementById('dhtmlgoodies_bmi_calculator'); calculatorGraphObj = document.getElementById('bmi_calculator_graph'); if(!useCm)document.getElementById('bmi_label_height').innerHTML = 'inches'; if(!useKg)document.getElementById('bmi_label_weight').innerHTML = 'pounds'; var heightInput = document.getElementById('bmi_height'); heightInput.onblur = validateField; var widthInput = document.getElementById('bmi_height'); widthInput.onblur = validateField; var labelDiv = document.createElement('DIV'); labelDiv.className = 'graphLabels'; calculatorGraphObj.appendChild(labelDiv); for(var no=graphLabels.length-1;no>=0;no--){ var colorDiv = document.createElement('DIV'); colorDiv.className='square'; colorDiv.style.backgroundColor = graphColors[no]; colorDiv.innerHTML = '<span></span>'; labelDiv.appendChild(colorDiv); var labelDivTxt = document.createElement('DIV'); labelDivTxt.innerHTML = graphLabels[no]; labelDiv.appendChild(labelDivTxt); labelDivTxt.className='label'; if((no+1)%labelsPerRow==0){ var clearDiv = document.createElement('DIV'); clearDiv.className='clear'; labelDiv.appendChild(clearDiv); } } var clearDiv = document.createElement('DIV'); clearDiv.className='clear'; labelDiv.appendChild(clearDiv); var graphDiv = document.createElement('DIV'); graphDiv.className='barContainer'; graphDiv.style.width = barWidth + 'px'; graphDiv.style.left = Math.round(((calculatorGraphObj.offsetWidth/2) /2) - (barWidth/2)) + 'px'; graphDiv.style.height = barHeight; calculatorGraphObj.appendChild(graphDiv); var totalHeight = 0; for(var no=bmiArray.length-1;no>0;no--){ var aDiv = document.createElement('DIV'); aDiv.style.backgroundColor = graphColors[no-1]; aDiv.innerHTML = '<span></span>'; var height = Math.round(barHeight * (bmiArray[no] - bmiArray[no-1]) / bmiArray[bmiArray.length-1]) - 1; aDiv.style.height = height + 'px'; graphDiv.appendChild(aDiv); } createWeightBar(1); } </script> <!-- function cal_bmi(lbs, ins){ h2 = ins * ins; bmi = lbs * h2/703 wtl = h2/703 * 24.9 f_bmi = Math.floor(bmi); diff = bmi - f_bmi; diff = diff * 10; diff = Math.round(diff); if (diff == 10){ f_bmi += 1; diff = 0; } bmi = f_bmi + "." + diff; return bmi; } function compute(){ var f = self.document.forms[0]; w = f.wt.value; v = f.htf.value; u = f.hti.value; // Format values for the calculation if (!chkw(u)){ var ii = 0; f.hti.value = 0; } else { var ii = parseInt(f.hti.value); } var fi = parseInt(f.htf.value * 12); var i = fi + ii; // Do validation of remaining fields if (!chkw(v)){ alert("Please enter your height."); f.htf.focus(); return; } if (!chkw(w)){ alert("Please enter your weight."); f.wt.focus(); return; } // Perform calculation f.bmi.value = cal_bmi(w, i); f.bmi.focus(); } function chkw(w){ if (isNaN(parseInt(w))){ return false; } else if (w < 0){ return false; } else{ return true; } } // --> </style> </head> <body> <div id="wrapall" align="center"> <img src="index_01_01.jpg" alt="Hcg drops fat banner"> <br/> <div id="navigationbar"> <a href="http://www.hcgdropsfat.com"><img src=hcghomeog.jpg border=0></a> <img src="hcgblogo.jpg" alt="Hcg blog"/> <img src="hcgfaqo.jpg" alt="Hcg faq"> <img src="hcgresourceso.jpg" alt="Hcg resources"> <img src="hcgtestimonialso.jpg" alt="Hcg testimonials"> <img src="hcgsupporto.jpg" alt="Hcg support"> <img src="hcgordero.jpg" alt="Hcg order"> <div id="bmibar"> <div style="position: absolute; top: 515px; left: 170px"; style="font-family: arial"; align="left";> How much is your weight in <br/>relation to your height <br/> <!--BMI CALCULATOR SCRIPT--> <div id="dhtmlgoodies_bmi_calculator"> <div class="calculator_form"> <form name="bmi_calculator"> <table> <tr> <td><label for="bmi_height">Height</label>:</td><td><input class="textInput" type="text" id="bmi_height" name="bmi_height"> <span id="bmi_label_height">cm</span></td> </tr> <tr> <td><label for="bmi_weight">Weight</label>:</td><td><input class="textInput" type="text" id="bmi_weight" name="bmi_weight"> <span id="bmi_label_weight">kg</span></td> </tr> <tr> <td colspan="2"><input type="button" onclick="calculateBMI()" value="Find BMI"></td> </tr> </table> </form> </div> <div class="calculator_graph" id="bmi_calculator_graph"> </div> </div> <script type="text/javascript"> initBmiCalculator(); </script> </div> <div style="position: absolute; top: 515px; left: 405px"; style="font-family: arial"; align="left";> What is your BMI category? <br/>This will help determine <br/>how much you need to lose <br/><br/><div id="bmiscale">Underweight = Under 18.5 <br/>Normal weight = 18.5 – 24.9 <br/>Overweight = 25 – 29.9 <br/>Obesity = 30 or more <br/><br/> </div></div> <div style="position: absolute; top: 515px; left: 640px"; style="font-family: arial"; align="left";> Calculate approximately how <br/>much weight you should lose<br/> to be at a healthy BMI <!--REVERSE BMI CALCULATOR--> <td width="81%" valign="top"> <br/><div align="center" class="page_header">Reverse BMI Calculator</div><br/> <div align="center" class="main_text"></div> <form action="" method="post" name="BMI_input" class="main_text" id="BMI_input"> <div style="text-align: center;"><font face="Arial, Helvetica, sans-serif">Target BMI:<b> <input id="FormsEditField4" type="text" name="wt" value="24" size="3" maxlength="2" /> <br /> </b></font></div> <div style="text-align: center;"> <font face="Arial, Helvetica, sans-serif"> <input type="button" name="FormsButton1" value="Find Target Weight" id="FormsButton1" onclick="self.compute()" /> </font></div> <div style="text-align: center;"><font face="Arial, Helvetica, sans-serif">This is your Target Weight: <br /> <input id="FormsEditField5" type="text" name="bmi" value="" size="4" maxlength="5" /> </font></div> </div> </div> <div id="Hcgborder"> <h3></h3> <p align="left"><b> WHAT IS HCG? </b><BR/><BR/>In simple terms: its a hormone protein produced by pregnant women that when used as a homeopathic dietary supplement, will assist in a revolutionary cure to the traditional diet routine. <BR/><BR/><b>HCG is so unique from other diets in 3 major ways: </b> <br/><BR/><img src="muscletissue.jpg" alt="practice"style="float:right;" width="250px" height="250px"/> 1. USES HIGHEST FAT AS PRIMARY FUEL SOURCE FOR THE BODY - it begins to break down the abnormally high body fat as the primary fuel source (BURNS ALOT OF FAT!) <BR/>2. DOESNT EAT AT VITAL MUSCLE TISSUE - it will preserve and maintain lean body muscle (without HCG THE BODY WOULD DEPLETE VITAL MUSCLE TISSUE ON A LOW CALORIE DIET. Also if you burn muscle you also lose metabolism for each pound of muscle you lose you also lose 50 calories of metabolism) <BR/>3. WHILE MOST DIETS SLOW METABOLISM HCG ACTUALLY MAINTAINS IT EVEN AFTER THE DIET - because hcg maintains lean muscle and maintains metabolism, you keep your metabolism in check long after the diet program so you reset your bodys roaming weight. <BR/><BR/>THE HOMEOPATHIC DROPS YOU WILL FIND ON OUR SITE ARE ALL NATURAL <br/><BR/><b>HOW LONG HAS IT BEEN AROUND?</b> <BR/><BR/>HCG or (Human chorionic gonadotropin)<img src="nicefigure.jpg" alt="Hcg stored fat" style="float:right;" width="250px" height="250px"/> is a protein hormone </div><!--p1--> </div><!--Hcgborder--> <div id="Hcgborder2"> <p><b>hello</b></p> <p>Hello again</p> </div><!--Hcgborder2--> </div> </div><!--wrapall--> </body> </html> [CODE] Hi, I'm trying to make a calculator app; with a few differences. I have a text field with a numberpad below it, I got the numbers to show up in the text field, but am unsure as to how when I hit the enter button - it would store them in a variable?...I am also wondering as to how it would store current value and then allow me to input another value(maybe on the next page) and either subtract or add to it(the first value that is stored). I am also wondering how to get a decimal point in place(need it for currency). Any help would be greatly appreciated! Here is my code: Code: <html> <head> <script type = "text/javascript"> function decPoint(str){ if (str.indexOf('.') == -1) str += "."; var decNum = str.substring(str.indexOf('.')+1, str.length); if (decNum.length > 2) { alert("Invalid more than 2 digits after decimal") } else { alert("Valid no") } } var ent = document.write(document.getElementById("curamt").value); </script> </head> <body border = "1"; color = "blue";> <div id = "cur"> <p>amount is: <script>document.getElementById("amount").innerHTML = ent);</script> </p> <b>Please type in price of item:</b> <form name = "calculator"> <table border = "1"; color = "blue";> <tr> <td colspan = "3" width="75%" align = "center"> <input type = "tel" id = "curamt" name = "tinput" maxlength="4" size="6"> </td> </tr> <table> <tr> <td><input type = "button" name = "one" value = " 1 " onclick = "calculator.tinput.value += '1'"></td> <td><input type = "button" name = "two" value = " 2 " onclick = "calculator.tinput.value += '2'"></td> <td><input type = "button" name = "three" value = " 3 " onclick = "calculator.tinput.value += '3'"></td> </tr> <tr> <td><input type = "button" name = "four" value = " 4 " onclick = "calculator.tinput.value += '4'"></td> <td><input type = "button" name = "five" value = " 5 " onclick = "calculator.tinput.value += '5'"></td> <td><input type = "button" name = "six" value = " 6 " onclick = "calculator.tinput.value += '6'"></td> </tr> <tr> <td><input type = "button" name = "seven" value = " 7 " onclick = "calculator.tinput.value += '7'"></td> <td><input type = "button" name = "eight" value = " 8 " onclick = "calculator.tinput.value += '8'"></td> <td><input type = "button" name = "nine" value = " 9 " onclick = "calculator.tinput.value += '9'"></td> </tr> <tr> <td><input type = "reset" name = "clear" value = " c " onclick = "calculator.tinput.value = ''"></td> <td><input type = "button" name = "zero" value = " 0 " onclick = "calculator.tinput.value += '0'"></td> <td><input type = "submit" id = "amount" name = "enter" value = " e " onsubmit = "ent(); return false;"></td> </tr> </table> </table> </form> </div> </body> </html> Im trying to get all of these math functions into one table with each one going into an individual row. The following is what my Grad Assistant gave us as instructions..he is not real helpful..lol The goal of project to is to create a webpage that makes use of javascript to perform a dynamic number of operations. The program must first ask for a number of operations to perform (n).It is therefore required that a loop construct be used. The program will then ask the user n times what operation they would like to perform and the appropriate inputs for that operation. All of the operations will use integer type inputs except ceiling, floor, and round which will use float types. The required operations for this project will be 1. + 2. * 3. / 4. % 5. min 6. max 7. floor 8. ceil 9. round The output of each operation will be stored in a table. The required outputs for each row are the operation requested, the expression for the operation showing its structure (see below), the result of the operation and additionally a random number. The random number should be within one and the number of operations requested. (ex: 5 operations requested, random number is in the range 0-5) A sample of what this output will look like is shown here. let me know if you can help it is much appreciated..the course book does not cover most of what is being taught and in class time could be better spent self taught! lol ..midterms suck and its almost time for the weekend so I could really use some help!! thx again |