JavaScript - Parameters Not Being Passed Into Functions
I am working on this simple calculator that passes values from one function to another via paramters. I have used alert() to find what is being recieved, so far nothing.
here is my code: Code: <html> <head> <title>Rectangle Calculator</title> <script type="text/javascript"> function calcArea(l,w) { var area = l * w return area alert("area: " + perimeter) // doesnt work } function calcPerim(l,w) { var perimeter = 2*(l+w) return perimeter alert("perimeter: " + perimeter) // doesnt work } function calc() { var width width = document.calcForm.widthBox.value var length length = document.calcForm.lengthBox.value alert(length + width) // works calcArea(length, width) document.clacForm.areaBox.value = area calcPerim(length, width) document.clacForm.perimeterBox.value = perimeter } </script> </head> <body> <p><strong>Area and Perimeter Calculator</strong></p> <form name="calcForm"> <label>Enter Width of the rectangle:</label> <br /> <input type="text" name="widthBox" size="6" /> <br /><br /> <label>Enter Length of the rectangle:</label> <br /> <input type="text" name="lengthBox" size="6" /> <br /> <input type="button" onClick="calc()" value="calculate" /><br /><br /> <label>The area is:</label> <br /> <input type="text" name="areaBox" size="12" /> <br /><br /> <label>The perimeter is:</label> <br /> <input type="text" name="perimeterBox" size="12" /> <br /> </form> </body> </html> here is the link to my page: http://royalvillicus.com/school/calcdebug.html I appreciate the help Similar TutorialsI need to create a function with named getFontSize() needs one parameter named "id" and id is value of object in document then to create a variable named object to represent object return font size of text in object use style object to retrieve font size and use parseInt() function to get value of font size this is the code i came up with Code: function getFontSize(id) { // Returns the font size of the object with the value id var object=document.getElementById(id); fontsize=parseInt(object.style.fontSize); return(fontsize); } What should i change to make work/ Hi all, I've written the following script: Code: <!doctype html> <html> <head> <meta charset="utf-8"> <title>Keys2</title> <script type="text/javascript"> function keyPress(key){ document.getElementById('rect01').style.fill = "red"; } </script> <style> .button { width: 100px; padding-right:10px; height:2em; background-color:#FC3; border-radius:3px; color:#fff; font-weight:bold; } ul { list-style-type: none; padding: 0; margin-left:25px; } li { float:left; width:30px; margin-right:25px; padding:10px; height:2em; background-color:#FC3; font-size:xx-large; } </style> </head> <body> <div> <svg width="1000" height="200"> <rect x="25" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect01"/> <rect x="100" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect02"/> <rect x="175" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect03"/> <rect x="250" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect04"/> <rect x="325" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect05"/> <rect x="400" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect06"/> <rect x="475" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect07"/> <rect x="550" y="50" fill="#FFFFFF" stroke="#000000" width="50" height="150" id="rect08"/> </svg> </div> <div> <ul> <li><a href="#" class="button" onClick="keyPress(rect01);">A</a></li> <li><a href="#" class="button" onClick="keyPress(rect02);">B</a></li> <li><a href="#" class="button" onClick="keyPress(rect03);">C</a></li> <li><a href="#" class="button" onClick="keyPress(rect04);">D</a></li> <li><a href="#" class="button" onClick="keyPress(rect05);">E</a></li> <li><a href="#" class="button" onClick="keyPress(rect06);">F</a></li> <li><a href="#" class="button" onClick="keyPress(rect07);">G</a></li> <li><a href="#" class="button" onClick="keyPress(rect08);">H</a></li> </ul> </div> </body> </html> Now, I could write a version of the keypress function for each rectangle, but that seems like poor coding. Can anyone point out how I might restructure the function or the code so that I can pass the number in the onClick to the rectangle it refers to? Thanks Hello, Ok so the following code works. Code: function myFunction(myName) { alert("You are "+myName); } callFunction = "myFunction"; parameter = "Joe"; window[callFunction](parameter); However this code doesn't work: Code: function myFunction(myName, myAge) { alert("You are "+myName+" and "+myAge+" years old."); } callFunction = "myFunction"; parameter = "Bill,15"; parameter = parameter.split(","); window[callFunction](parameter); The above code alerts: "You are Bill,15 and undefined years old." Thanks for the help! Hi, I have written a number of functions designed to return frequency data on 1000 randomly chosen numbers using different math functions for the rounding. I would like to include all of these functions within the wrapper of another function so that only one call is needed to get returns from all of the 'inner' functions. However, while each of the functions works in isolation, the moment I wrap them in another function they stop working. The following code is one of the functions 'frequencyWrapperOne' that has been wrapped in the function 'testWrapper'. A call to testWrapper does nothing. Can anyone see what I'm doing wrong? Code: function testWrapper() { function frequencyWrapperOne() { var numberArrayOne = new Array(0,0,0); for (var i = 0; i < 1000; i = i + 1) { var chosenNumber = Math.floor(Math.random() * 3); if (chosenNumber == 0) { numberArrayOne[0] = numberArrayOne[0] + 1; } if (chosenNumber == 1) { numberArrayOne[1] = numberArrayOne[1] + 1; } if (chosenNumber == 2) { numberArrayOne[2] = numberArrayOne[2] + 1; } } return window.alert(numberArrayOne.join(',')); } } testWrapper(); Thanks. i have this code: PHP Code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } then i have my JS: [CODE] thank you all but i am totally confused now...here is my full code: <?php foreach ($freechat_list as $r) { $uniqueCode = substr($r,0,12); $id = substr($r,13); $blocked_record = RcBlockListTablePeer::isBlocked($id,$requestor_id); ?> <a href="#" id="profilelink" name="profilelink" onClick="return viewornot(<?php echo $id."/".$blocked_record; ?>)"><?php echo $uniqueCode; ?></a> } my JS: Code: function viewornot(id) { alert(id); } alert(id) only gives me the id but in my href i concatenated it with blocked_record: viewornot(<?php echo $id."/".$blocked_record; ?>) please help? I know I have a thread about the sorting function I'm about to post, but this problem doesn't deal with the sorting itself, but rather the fact that a variable is not passing. The code below is the relevant part to an autosuggest feature. The variable that isn't being passed is "firstValidIndex". It is being set appropriately, but when it is used in "sortArray()", its value is 0. Code: // here we must check to see if where the string matched was at the beginning of a string inside this.aNames // firstValidIndex is the first index where the char is at the beginning of a string var firstValidIndex; loop1: for(var j in firstIndices) { loop2: for(var k in allOccurrences) { if(allOccurrences[k] == firstIndices[j]) { firstValidIndex = firstIndices[j]; aList.push(this.aNames[i]); ctr++; break loop1; break loop2; } } } function sortArray(a,b) { var lca = a.toLowerCase(); var lcb = b.toLowerCase(); var lco = str.toLowerCase(); var diff = lca.indexOf(lco,firstValidIndex) - lcb.indexOf(lco,firstValidIndex); // some debugging code here alert("Comparing "+lca+" with "+ lcb+"\nDiff:"+diff+"\nFirst Valid Index: "+firstValidIndex); if ( diff < 0 ) return -1; if ( diff > 0 ) return 1; return 0; } aList.sort(sortArray); Hello, I am trying to use .innerHTML to replace an image with an embedded flash file. Here is my code... HTML: Code: <a href="#" onclick="funt1(); return false;">do it to it</a><br><br> <span id="embed"><img src="video%20convert%20zone/zerotime.png"></span> JavaSscript: Code: <script type="text/javascript"> function funt1(){ document.getElementById('embed').innerHTML='<object width="100" height="40"><param name="movie" value="video%20convert%20zone/video.swf"></param><embed src="video%20convert%20zone/video.swf" width="100" height="40" name="player" id="player" menu="false" loop="false" bgcolor="#000000" wmode="transparent" type="application/x-shockwave-flash"></embed><param name="loop" value="false"></param><param name="menu" value="false"></param><param name="bgcolor" value="#000000"></param><param name="wmode" value="transparent"></param></object>'; return false; } </script> And for some reason in Internet Explorer when I click the "do it to it" link, the image just disappears, and object and embed don't appear. But it works in Firefox. Any suggestions? Image of the output: http://i.imgur.com/jqzhJxb.png What I'm trying to do, is pass an object by reference so that I can use it in other scripts, and allow the current script to change the object's value when appropriate. What's happening: It passes correctly, you can see that my var_dump of the object before the function call is 30. After the function call, it becomes 60. Also, it writes "now60" to the document as instructed. When I call the function the second time, it does nothing. No error, no repeat of writing now60 to the document, etc. And in the last var_dump, which is after the second function call - you can see that the value remained 60. Why? Thanks for your help! Code: PHP Code: var quickChallengeTimer = {timer:30}; var quickChallengeQuestion; var quickChallengeAnswer; var quickChallengeResponse; function quickChallenge(quickChallengeTimerfunc, quickChallengeQuestion, quickChallengeAnswer) { if (typeof quickChallengeResponse == 'undefined') { switch (quickChallengeTimerfunc.timer) { case 30: quickChallengeTimerfunc.timer = 60; quickChallengeResponse = 'undefined'; document.write("now60"); break; case 60: quickChallengeTimerfunc.timer = 120; quickChallengeResponse = 'undefined'; document.write("now120"); break; default: document.write("Error"); break; } } console.dir(quickChallengeTimerfunc.timer); } var_dump(quickChallengeTimer); quickChallenge(quickChallengeTimer); var_dump(quickChallengeTimer); quickChallenge(quickChallengeTimer); var_dump(quickChallengeTimer); Hi all, I have a newbie question. I have just started working with javascript and would appreciate some guidance. I have a webpage and there are products for sale on it(this is not live it is merely being used as practice project). Beside each product is a description a price and an 'add to cart' button. My cart is simply a div with an id of 'cart' and it has a text box within it. I need the product name to be displayed within the div (this, I have working), I also need to display the product price in the text box once the button(add to cart ) for that particular product has been pressed. Also when the button for another product is pressed, I want the cost/value for that product to be added to the other value and displayed in the text box in the cart div... I apologise for rambling on but this is the best way of me explaining my needs.... Here's where i am right now.. The HTML snippet Code: <div id ="cart"> <p><img src="images/shopping-cart.png" alt ="cart"/>Your Cart</p> <div id="sum"><!--(this is the div where the total goes)--> <input type="text" id="total" value="0" /><p>€ Your Total <input type="reset" value = "reset" /></p> </div> </div> <h2 id ="black">Blackcurrent<br /></h2> <p>€ 12.00 <input type = "submit" value ="add to cart" onClick = "shoppingCart('Blackcurrent',12)" /></p> And the javascript: Code: alert ("working"); function shoppingCart (itemName,itemValue) { /* var thePrice = Number(itemValue); return thePrice;*/ document.getElementById ("cart").innerHTML += itemName + "<br/>"; document.getElementById('total').value = Number(document.getElementById('total').value) + itemValue; } I hope i have posted correctly and am aware that i have only posted a segment of the HTML.. Please let me know if you need any more code or info.. Thanks a lot in advance for any help... Hi, Could I stablish parameters to .html or .asp (principally) dealing with width, height, color, etc. like this? Quote: <ASP:FILE ID = "oApp" APPLICATIONNAME = "Drive coll and obj" BORDER = "thin" CAPTION = "yes" ICON = "/images/book.ico" SHOWINTASKBAR = "yes" SINGLEINSTANCE = "yes" SYSMENU = "yes" WINDOWSTATE = "maximize" SCROLL = "yes" SCROLLFLAT = "yes" VERSION = "1.0" INNERBORDER = "yes" SELECTION = "yes" MAXIMIZEBUTTON = "yes" MINIMIZEBUTTON = "yes" NAVIGABLE = "yes" CONTEXTMENU = "yes" BORDERSTYLE = "normal" > Best for now just he! Ok here is what I have so far, my ending part of my Call Function I think is ok. for my main function. I think I misplaced the { and } I will show you all the codes I have for my main function this is what I have I think I did misplace something but I can not pin point where that one small things should be Code: unction showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } for (var i=0; i < name.length; i++) { document.write("<tr>"); document.write("<td>" name[i] + "(" + party[i] + ")</td>"); document.write("td class='num'>" + votes[i] + "</td>"); var percent=calcPercent(votes[i], totalV) document.write("<td class='num'>(" + percent +"%)</td>"); createBar(party[i],percent) document.write("</tr>"); } document.write("</table>"); } </script> Just wondering if i misplaced any ; or { or } anywhere suggestions? Here is my call function Code: <script type="text/javascript"> showResults(race[0],name1,party1,votes1); showResults(race[1],name2,party2,votes2); showResults(race[2],name3,party3,votes3); showResults(race[3],name4,party4,votes4); showResults(race[4],name5,party5,votes5); </script> I been going over this, I can not seem to figure out what { i might be missing? Thanks Is there a way to activate a function from another function? It has to be in the script tag, it can't be in the HTML section. Can I use something similar to this following code? If not, can anyone give me some help? I have tried to do it various ways, and have looked it up a few times, but to no avail. Can I use something similar to this following code? If not, can anyone give me some help? if (condition) {activate functionname();} Any help I can get would be appreciated. Thanks a lot to anyone who can help. Code: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email, courseID, titleArray, pointsArray){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; this.title = titleArray; this.points = pointsArray; this.assign = this.points.slice(0,4); this.exams = this.points.slice(-2); this.assignments = function() { return task(this.title,this.points); } this.totalPoints = function() {return addExam(this.assign,this.exams); } this.finalGrade = calcGrade; } Student.prototype = { constructor : Student, toString : studentInfo }; //assign and exam doesn't seem to hold no values inside.. ??? function addExam(assign,exams){ var exams=this.exams; var high1=exams[0]; var high2=0; while(high2<exams.length){ high1=Math.max(high1,exams[high2]); high2++; } var sum = 0; for (var i=0; i < assign.length; i++){ sum += assign[i]; } return sum + high1; } var totalPoints = addExam(); function calcGrade(){ var grade; if (totalPoints >= 190){ return "A+"; }else if (totalPoints >= 180){ return "A"; }else if (totalPoints >= 175){ return "B+" }else if (totalPoints >= 170){ return "B"; }else if (totalPoints >= 165){ return "B-"; }else if (totalPoints >= 160){ return "C"; }else if (totalPoints >= 150){ return "D"; }else if (totalPoints < 150){ return "F"; } } function studentInfo(){ return "Student : " + this.lastName + "," + this.firstName + "<br>"+ "eMail : " + this.email + "<br>" + "Course ID : " + this.courseID + "<br>" + "--------------------------------" + "<br>" + this.assignments() + "--------------------------------" + "<br>" + "Total Points : " + this.totalPoints() + "<br>" + "Final Grade : " + this.finalGrade(); } function createStudents(){ var student1 = new Student("Jake", "Hennry", "jhennery@gmail.com","COIN-070B.01", ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"], [25, 25, 28, 20, 29, 40, 40] ); alert("Student : " + student1.lastName + "," + student1.firstName + "\n"+ "eMail : " + student1.email + "\n" + "Course ID : " + student1.courseID + "\n" + "---------------------------------------" + "\n" + student1.assignments() + "\n" + "---------------------------------------" + "\n" + "Total Points : " + student1.totalPoints() + "\n" + "Final Grade : " + student1.finalGrade()); } var titleArray = ["Assignment1","Assignment2","Assignment3","Assignment4","Assignment5","MidTerm", "Final"]; var pointsArray = [30, 30, 28, 27, 29, 41, 45]; var student = new Student("Haripriyaa", "Ganesan", "haripriyaa@gmail.com","COIN-070B.01", titleArray, pointsArray ); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> Hello, I have a question. If I include js like this: <script type="text/javascript" src="code.js?ver=1"></script> If this include makes browser to always download js script? or does he use script from catch? I need this for changing ver number for browser to know when to redownload script. maybe is other way to redownload js script just when js script content is changed? P.S. Sorry for my bad english. (I hope you understand what I wanted to ask) Regards, sAdFella i m trying to implement captcha in my site.i m using recaptcha. To check the captcha i need to request url like: http://www.google.com/recaptcha/api/verify?privatekey="key"&remoteip="ip"&challenge="chal"&response="res" and then i need to check response from url if it is true or false i dont know how to request response from url help plz Hi, I am making a function that executes code as AJAX readyState's are returned... If readyState = 3 then I running code through eval but I want to be able to run functions with parameters, within the parameter that is evetually executed by the eval Heres abit of pseudo code of what I am talking about Code: function receiveRequest(whileLoading, whenDone) { // AJAX stuff... blah... blah... blah... if request is being processed: eval(whileLoading) if request is done: eval(whenDone) } // When a button is clicked: onClick="receiveRequest('alert('loading')', 'alert('finished AJAX request')')" But this doesn't work because I am escaping the first parameter of 'receiveRequest' in the alert() but if I use double quote (") I will be escaping the event handler Is there anyway to get around this / or a better way to fix it? I haven't used Javascript in agggeeesss and I can barely remember anything anymore - PHP <3 Thanks in advanced. I am to make a showresults function, purpose is for results 4 parameters are in function, race, name,party and votes i then declare variable named totalV equal to value of returned by the totalVotes() function useing votes as parameter value then write HTML code to document this is the code I came up with Code: function showResults(race,name,party,votes) { // script element to display the results of a particular race var totalV = totalVotes(votes); document.write("<h2>" + race + "</h2>"); document.write("<table cellspacing='0'>"); document.write("<tr>"); document.write("<th>Candidate</th>"); document.write("<th class ='num'>Votes</th>"); document.write("<th class='num'>%</th>"); document.write("</tr>"); } How does this look so far? Code: function viewDetails(rowid,linkid){ alert("enterining into bundles"); if(linkid=='seobundles') { alert("enetering into if "); document.chwAnnouncementW.action='${contextPath}'+"/dolphin.wss/viewSeobundleW?rowindex="+rowid; document.chwAnnouncementW.submit(); } else { alert(linkid); document.chwAnnouncementW.action='${contextPath}'+"/dolphin.wss/viewSeoW?rowindex="+rowid; document.chwAnnouncementW.submit(); } } Actually i am passing linkid="seobundles" as string but its not interpreting and it is always going to else part and not if part. I tried to print link id its teling its of object HTML table type and we are passing the two parameters rowid, linkid from a macro. rowid is working fine as and when we select radio buttion but linkid is not working as an string. IF i pur linkid in single quotes then also its not working My java skill are rudimentary at best. I have an email which has some values attached to a link in the email that get passed to an online form on a website when clicked. Problem is the value is a price and the string includes a "$" which I need to remove. I've read through many examples and everyone seems to have an opinion (surprise). One suggests something like this: Code: text2.value=text1.value.replace(/\$/g,""); While someone else says its better to remove what you don't want. I am also scratching my head over should I place the value into a hidden field, scrub it then copy that into the proper field? and I imagine the best way would be to run it with an "onload" command instead or a event handler like a keystroke since the field is not typed? Roundtable discussion would be appreciated to help me solve this simple problem and help expand my knowledge of java... thanks. Hello, I am trying to update an iframe when the user makes a selection from a select box. I don't have any trouble with changing the iframe, but when I try to send a varible as a quey string, the variable doesn't pass to the iframe properly. // this is in my header, and it is initiated from the onchange below. // it changes the page fine, but doesn't read the varible "num" // that was passed to the function <script language="javaScript"> <!-- function updatenotes (num) { document.getElementById("desc").src = 'iframe1.cfm?dec=num' } //--> </script> // this is the select box that initiates the function from onchange // for simplicities sake, I hard coded 3 options, but in reality, // these options are ever changing <select name="Description" onchange="updatenotes(this.options[selectedIndex].value)"> <option name="">Select a project</option> <option name="2" >project2</option> <option name="3" >project3</option> </select> Any help you can offer would me ver appreciated. thanks |