JavaScript - Problem With A Simple Math Formular
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 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> 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? 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? 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 Hi. I'm in JS kindergarten. I have a form with a field that asks for a full year. If the year is greater than 20 years ago, I'd like additional form fields to be revealed. If the year is equal to or less than 20 years ago, it will not reveal the fields. (And it should be based on getFullYear(), so I don't have to update the script every year, yeah?) I figured out how to script onclick functions and some basic .value == functions in order to show/hide just about every type of form field. So I don't need that info. But I'm unsure of how to calculate the value. I'd be interested to see your solutions. No rush. Thanks in advance. Hey guys, I'm new to jquery and I'm sure this is a VERY simple problem.. Here's my code Quote: <style type="text/css"> #box { background: red; width: 300px; height: 300px; display: none; } </style> <script type="text/javascript"> $(function() { $('a').click(function() { $('#box').slideDown(4000); }); }); </script> </head> <body> <div id="box"></div> <a href="#">Click Me!</a> </body> </html> As you can see it's pretty simple, I've made the box slideIn. My problem is I want to make a separate button to slide it back out, but because I've used the "a" tag it's associating all links with the same function, how do I get around this? I'm sure it's really simple! Thanks Hi all, I'm pretty new to javascript coding and was trying to make a fading image slideshow. i have found one on dynamicdrive modified it, all looks fine. The first image shows and thats it. doesnt go through the photos :/ probably something simple but i cant work it out, any thoughts? EDIT: Code: <head> <script language="javascript1.1"> var mygallery=new fadeSlideShow({ wrapperid: "column2", dimensions: [250, 180], imagearray: [ ["images/img1.png"], ["images/img2.png"], ["images/img3.jpg"] ], displaymode: {type:'auto', pause:2500, cycles: 10, wraparound:false}, persist: false, fadeduration: 500, descreveal: "ondemand", togglerid: "" }) </script> </head> <body> <div id="column2"><a href="#" class="next"><img src="images/img1.png" name="slide" id="rounded-image" height="288" border="0" style="filter:blendTrans(duration=3)" alt="image-1"/></a></div> </body> Thanks, Storm08 Hello, Just trying to combine php variable with some javascript in a simple if ... else. This is the script code in php: Code: <script type="text/javascript"> var the_rad_val=<?php echo $N_rad_val;?>; if (the_rad_val.value='n') { function removeLink(); } else { function restoreLink(); } </script> This is how it looks in the browser (source) Code: <script type="text/javascript"> var the_rad_val=n; if (the_rad_val.value='n') { function removeLink(); } else { function restoreLink(); } </script> The 2 functions a Code: function removeLink() { document.getElementById("mydiv").style.visibility = "hidden"; } function restoreLink() { document.getElementById("mydiv").style.visibility = "visible"; } // end function Guess I did something wrong because the "mydiv" is visible when it shouldn't be Can someone help me out as I am not too good with javascript . Thank you. . 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;} 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. 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> 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'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 Hello I would like to know how this is not functional. surely passing the function to another function would work so I can use the same variables without having to write it out again. [ICODE] <html> <head> <title>Number Conversions</title> <script> function addNumbers () { var firstnumber = document.calculator.myFirstNumber.value; var secondnumber = document.calculator.mySecondNumber.value; var total = parseInt(firstnumber) + parseInt(secondnumber); document.calculator.myTotal.value = total; document.calculator.myHex.value = total.toString(16); document.calculator.myOct.value = total.toString(8); document.calculator.myBinary.value = total.toString(2); document.write("End of Calculation."); } function subtractNumbers (addNumbers) { var total = parseInt(firstnumber) - parseInt(secondnumber); } </script> </head> <body> <form name="calculator"> First Number <input type=text name="myFirstNumber" value=0 size=3> <br> Second Number <input type=text name="mySecondNumber" value=0 size=3><br><br> <input type="button" value="ADD" onclick="addNumbers();"> <input type="button" value="SUBTRACT" onclick="subtractNumbers();"><br> Total <input type=text name="myTotal" value=0 size=3><br> Binary <input type=text name="myBinary" value=0 size=8><br> Octal <input type=text name="myOct" value=0 size=3><br> Hexidecimal <input type=text name="myHex" value=0 size=3><br> </form> </body> </html> [ICODE] Hi folks this is my first post Edit: sorry for the incorrect title should have read simple javascript validation problem! i have a fair understanding of php and mysql and have never had to use javascript as i was secretly trying to avoid it. The time has now come where i want to use it for client side validation on a form. I am able to validate most of fields however i need to validate a date to check it has been entered in the following format dd/mm/yyyy and that the date is not greater than todays date. N.B the date is entered into a text field in HTML i wrote a function with lots of if/else statements and failed. Im 100% positive there is a far simpler way to achieve my goal any help would be greatly appreciated. Thanks Code: function checkDate(elem, helperMsg){ var day = elem.substr(0,2); var month = elem.substr(3,2); var year = elem.substr(6,4); if(day < 01 || day > 31) { var invalidday = true; } if (month < 0 || month > 12) { var invalidmonth = true; } if (year < 01 || year > 2099) { var invalidyear = true; } if ( month==04 || month==06 || month==09|| month==11) { if (day == 31) { var invalidday = true; } } if (month==02) { if (day > 28) { var invalidday = true; } } if (invalidday || invalidmonth || invalidyear) { alert(helperMsg); elem.focus(); return false; } else { var dd = today.getDate(); var mm = today.getMonth()+1;//January is 0! var yyyy = today.getFullYear(); if(dd < 10) { dd='0'+dd; } if(mm < 10) { mm='0'+mm; } } if (day > dd && month > mm && year > yyyy) { alert(helperMsg); elem.focus(); return false; } else { return true; } } Hey guys, so I am a designer (not a developer) doing a site for someone. I am playing with some simple free javascripts. I have lightbox and toggler. Both work great individually. They are conflicting and everywhere online says to set the both to onLoad in the body tag. Sounds easy enough. But I can't seem to figure out the call for this script: Code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="../js/expand.js"></script> <script type="text/javascript"> $(function() { $("h2.expand").toggler({method: "fadeToggle"}); }); //--><!]]> </script> <body onload="toggler();initLightbox()"> is what is seems like it should be for me. But that isn't working at all. Please help! I feel like I have tried every possible name with the toggler()... If you need more, I can point you to the site itself and you can see all of the (messy) code. Hi i am trying to combine these two statments Code: searchValue.replace( /\[[^\)]*\]/g,""); searchValue.replace( /\([^\)]*\)/g, ""); is it possible to put these two into one statment? also is there a javascript function which does the same as urlencode? many thanks Luke I have a script that includes a JS delete function, but when I select a record and hit delete it says no record is selected. I'm sure this is a simple fix for someone in the know. Thanks in advance. Site: PHP Code: <?php require_once('auth.php'); ?> <script type="text/javascript" src="script.js"> </script> <?php include("header.php"); ?> <b><div align="right"><a href="admin-index.php">Admin</a> - <a href="adminorders.php">Orders</a> - <a href="adminmain_forum.php">Support</a> - <a href="register-form.php">Add User</a> - <a href="adminlogout.php">Logout</a></div></b><br> <b>Report Upload</b> <br>To upload reports after completion use the form below and update the order with the report URL (/reports/filename). <center><form action="./uploadadmin.php" method="post" enctype="multipart/form-data"> <p> <label for="file">Select a file:</label> <input type="file" name="userfile" id="file"> <br /> <p><button>Upload File</button> <p> </form></center> <p><b>Previous Orders</b> <br>Details of previous orders and trials are displayed below. <br><script> <!-- Hide from old browsers /****************************************** * Find In Page Script -- Submitted/revised by Alan Koontz (alankoontz@REMOVETHISyahoo.com) * Visit Dynamic Drive (http://www.dynamicdrive.com/) for full source code * This notice must stay intact for use ******************************************/ // revised by Alan Koontz -- May 2003 var TRange = null; var dupeRange = null; var TestRange = null; var win = null; // SELECTED BROWSER SNIFFER COMPONENTS DOCUMENTED AT // http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html var nom = navigator.appName.toLowerCase(); var agt = navigator.userAgent.toLowerCase(); var is_major = parseInt(navigator.appVersion); var is_minor = parseFloat(navigator.appVersion); var is_ie = (agt.indexOf("msie") != -1); var is_ie4up = (is_ie && (is_major >= 4)); var is_not_moz = (agt.indexOf('netscape')!=-1) var is_nav = (nom.indexOf('netscape')!=-1); var is_nav4 = (is_nav && (is_major == 4)); var is_mac = (agt.indexOf("mac")!=-1); var is_gecko = (agt.indexOf('gecko') != -1); var is_opera = (agt.indexOf("opera") != -1); // GECKO REVISION var is_rev=0 if (is_gecko) { temp = agt.split("rv:") is_rev = parseFloat(temp[1]) } // USE THE FOLLOWING VARIABLE TO CONFIGURE FRAMES TO SEARCH // (SELF OR CHILD FRAME) // If you want to search another frame, change from "self" to // the name of the target frame: // e.g., var frametosearch = 'main' //var frametosearch = 'main'; var frametosearch = self; function search(whichform, whichframe) { // TEST FOR IE5 FOR MAC (NO DOCUMENTATION) if (is_ie4up && is_mac) return; // TEST FOR NAV 6 (NO DOCUMENTATION) if (is_gecko && (is_rev <1)) return; // TEST FOR Opera (NO DOCUMENTATION) if (is_opera) return; // INITIALIZATIONS FOR FIND-IN-PAGE SEARCHES if(whichform.findthis.value!=null && whichform.findthis.value!='') { str = whichform.findthis.value; win = whichframe; var frameval=false; if(win!=self) { frameval=true; // this will enable Nav7 to search child frame win = parent.frames[whichframe]; } } else return; // i.e., no search string was entered var strFound; // NAVIGATOR 4 SPECIFIC CODE if(is_nav4 && (is_minor < 5)) { strFound=win.find(str); // case insensitive, forward search by default // There are 3 arguments available: // searchString: type string and it's the item to be searched // caseSensitive: boolean -- is search case sensitive? // backwards: boolean --should we also search backwards? // strFound=win.find(str, false, false) is the explicit // version of the above // The Mac version of Nav4 has wrapAround, but // cannot be specified in JS } // NAVIGATOR 7 and Mozilla rev 1+ SPECIFIC CODE (WILL NOT WORK WITH NAVIGATOR 6) if (is_gecko && (is_rev >= 1)) { if(frameval!=false) win.focus(); // force search in specified child frame strFound=win.find(str, false, false, true, false, frameval, false); // The following statement enables reversion of focus // back to the search box after each search event // allowing the user to press the ENTER key instead // of clicking the search button to continue search. // Note: tends to be buggy in Mozilla as of 1.3.1 // (see www.mozilla.org) so is excluded from users // of that browser. if (is_not_moz) whichform.findthis.focus(); // There are 7 arguments available: // searchString: type string and it's the item to be searched // caseSensitive: boolean -- is search case sensitive? // backwards: boolean --should we also search backwards? // wrapAround: boolean -- should we wrap the search? // wholeWord: boolean: should we search only for whole words // searchInFrames: boolean -- should we search in frames? // showDialog: boolean -- should we show the Find Dialog? } if (is_ie4up) { // EXPLORER-SPECIFIC CODE revised 5/21/03 if (TRange!=null) { TestRange=win.document.body.createTextRange(); if (dupeRange.inRange(TestRange)) { TRange.collapse(false); strFound=TRange.findText(str); if (strFound) { //the following line added by Mike and Susan Keenan, 7 June 2003 win.document.body.scrollTop = win.document.body.scrollTop + TRange.offsetTop; TRange.select(); } } else { TRange=win.document.body.createTextRange(); TRange.collapse(false); strFound=TRange.findText(str); if (strFound) { //the following line added by Mike and Susan Keenan, 7 June 2003 win.document.body.scrollTop = TRange.offsetTop; TRange.select(); } } } if (TRange==null || strFound==0) { TRange=win.document.body.createTextRange(); dupeRange = TRange.duplicate(); strFound=TRange.findText(str); if (strFound) { //the following line added by Mike and Susan Keenan, 7 June 2003 win.document.body.scrollTop = TRange.offsetTop; TRange.select(); } } } if (!strFound) alert ("Order '"+str+"' not found!") // string not found } // --> </script> <!-- EXAMPLE FORM OF FIND-IN-PAGE SEARCH USING SUBMIT (ALLOWING 'ENTER/RETURN' KEY PRESS EVENT) --> <center><b>Enter order number</b> <form name="form1" onSubmit="search(document.form1, frametosearch); return false"><input type="text" name="findthis" size="15" title="Press 'ALT s' after clicking submit to repeatedly search page"> <input type="submit" value="Search Orders" ACCESSKEY="s"></form></center> <br><br><table width="775" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td> <form action="" method="post" name="" id=""> <table width="600" border="1" align="center" cellpadding="2" cellspacing="2"> <tr> <td><input name="topcheckbox" type="checkbox" class="check" id="topcheckbox" onClick="selectall();" value="ON"> Select All </td> <td colspan="4" align="center"><a href="form.php?mode=add">Add New Order</a></td> </tr> <tr> <td><strong><a href="javascript:goDel()">Delete</a></strong></td> <td><strong>Order Number</strong></td> <td><strong>Order Status</strong></td> <td><strong>Payment Status</strong></td> <td><strong>Update</strong></td> </tr> <? include("conn.php"); $sql="select sn,branchname,shortname,payment from $branch order by sn"; $result=mysql_query($sql,$connection) or die(mysql_error()); while($row=mysql_fetch_array($result)) { ?> <tr> <td><input name="<? echo $row['sn']; ?>" type="checkbox" class="check"></td> <td><? echo $row['branchname']; ?></td> <td><? echo $row['shortname']; ?></td> <td><? echo $row['payment']; ?></td> <td><a href="<? echo "form.php?sn=".$row['sn']."&mode=update"; ?>">Update</a></td> </tr> <? } ?> <tr> <td><strong><a href="javascript:goDel()">Delete</a></strong></td> <td><strong>Order Number</strong></td> <td><strong>Order Status</strong></td> <td><strong>Payment Status</strong></td> <td><strong>Update</strong></td> </tr> </table> </form></td> </tr> </table> <?php include("footer.php"); ?> JS File Code: function goDel() { var recslen = document.forms[0].length; var checkboxes="" for(i=1;i<recslen;i++) { if(document.forms[0].elements[i].checked==true) checkboxes+= " " + document.forms[0].elements[i].name } if(checkboxes.length>0) { var con=confirm("Are you sure you want to delete"); if(con) { document.forms[0].action="delete.php?recsno="+checkboxes document.forms[0].submit() } } else { alert("No record is selected.") } } function selectall() { // var formname=document.getElementById(formname); var recslen = document.forms[0].length; if(document.forms[0].topcheckbox.checked==true) { for(i=1;i<recslen;i++) { document.forms[0].elements[i].checked=true; } } else { for(i=1;i<recslen;i++) document.forms[0].elements[i].checked=false; } } |