JavaScript - Setting An Array As Arguments
I am a newbie and am writing a function. I want the function to refer to an arrays elements to get the biggest, but I dont know how to do this.
Here is the code: Code: function unique(first,second,third) { var answer; if (first > second) { answer = first - second; } if (second > third) { answer = second - third; } if (third > first) { answer = third - first; } return answer; } //function call unique (digitArray(0,1,2)); what I am trying to do, is get the array elements to be called and give me an answer. Will I need to add the array to the function? It is further down the code after the function at the moment. Or will I need to add the array elements to the function? Hope it is clear Similar TutorialsCode: <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> Hi, I'm banging my head off a brick wall with setting up a 3 dimensional array and trying to loop through it. I'm using the EJS framework (http://embeddedjs.com/). We currently have a 2D array set up to list out features. See below: topfeatures: [ "Feature 1", "Feature 2", "Feature 3", "Feature 4", "Feature 5", "Feature 6" ] <ul> [% for(var i = 0; i < this.topfeatures.length; i++) { %] <li>[%= this.topfeatures[i] %]</li> [% } %] </ul> However, the request we have requires headlines for each set of features. Headline 1 Feature1 Feature2 Feature3 Headline 2 Feature4 Feature5 Feature6 Any ideas how I can do this? Hello im making a search program and the results are displayed in HTML, i decided i wanted a link after each line in an innerHTML div, the problem is i cant set the id dynamicly i have the class is to style. .innerHTML = "<a id = 'myarray[arraycounter]' class = 'innerLink' href = 'javascript:'>View camp information</a>" but this dosent work. i also tried using " thinking that it was because it needed double quotes but this still didnt work. when i inspect the element in chrome it just comes up as array[value]. please help me out guys i need a way to dynamicly give it a link. Hi all, I am trying to pass some dynamic values for use with javascript or more specifically AJAX... I had a set up looking something like the following; Code: <input type="button" onclick="ajaxFunction()" value="Add Favourite"/> <input type="text" name="school_id" id="school_id" value="<?php echo $school_id; ?>" /> <input type="text" name="teacher_id" id="teacher_id" value="<?php echo $teacher_id; ?>" /> Code: <script language ="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); }catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data // sent from the server and will update // div section in the same page. ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.value = ajaxRequest.responseText; } } // Now get the value from user and pass it to // server script. var school_id = document.getElementById('school_id').value; var teacher_id = document.getElementById('teacher_id').value; var queryString = "?sid=" + school_id; queryString += "&tid=" + teacher_id; alert(queryString); ajaxRequest.open("GET", "ajax_insert_favourite.php" + queryString, true); ajaxRequest.send(null); } //--> </script> however because it is possible for there to be more than one button, i.e. many teachers can be returned the javascript would also output 1 and 1. I need someway of making this unique to the id's... I think that passing arguments/params might be the solution but I'm having a hard time implementing it; I've tried the following; Code: <input type="button" onclick="ajaxFunction('school_id','teacher_id')" value="Add Favourite"/> Code: <!-- //Browser Support Code function ajaxFunction(school_id,teacher_id){ But once I do this, it no longer even make the call. Can anyone advise here, I'm a relative newbie to javascript/AJAX etc. Many thanks, Greens85 Should be simple, but I'm having a complete brain fart. I need to call a function, with a parameter that triggers something relative to that parameter. Pseudo Example Code: function respawn(n) { case 1 //respawn monster1 code case 2 //respawn monster 2 code case 3 //respawn monster 3 code } if(killed monster1) {respawn(1)} //respawn(monster1) is what I want to do if(killed monster2) {respawn(2)}//respawn(monster2) is what I want to do if(killed monster3) {respawn(3)}//respawn(monster3) is what I want to do I can... Code: function respawn1(){ //respawn monster1 code } function respawn2() { //respawn monster2 code } function respawn3() { //respawn monster3 code } if(killed monster1) {respawn1()} if(killed monster2) {respawn2()} if(killed monster3) {respawn2()} but if I have 10+ monsters I just figured a case structure would be good, or passing the monster to respawn to a single respawn() function......but all the switch examples I could find were based on dateTime which gave case 1-7 based on what day it was, and didn't show how you set your own cases like monster1, monster2, monster3.... I know this is a basic concept...I've read about functions he http://www.quirksmode.org/js/function.html and at w3schools of course but can't figure out how to apply it to my situation Thanks I want to use the new keyword to instantiate an object. The catch is I want to pass in variable length arguments. Given: Code: function Foo () { this.args = Array.prototype.join.call (arguments); } var args = ["arg0", "arg1", "arg2"]; The following don't work (though I understand why): Code: new Foo.apply (null, args); new (Foo.apply (null, args)); (new Foo).apply (null, args); Any ideas on how to do what I want without modifying Foo's source code? i've got a project to be done using javascript and html....i don't know how to pass the arguments from <input type="text"> to the javascript function i'm using in my program. i just want the javascript script to calculate the input given by the user and return the answer. here is the program: Code: <html> <head> <title> Taxi Fare </title> <script lang="text/javascript"> // calculates taxi fare based upon miles traveled // and the hour of the day in military time (0-23). var taxiFare = function (milesTraveled, pickupTime) { var baseFare = 2.50; var costPerMile = 2.00; var nightSurcharge = 0.50; // 8pm to 6am, every night var cost = baseFare + (costPerMile * milesTraveled); // add the nightSurcharge to the cost if it is after // 8pm or before 6am if (pickupTime >= 20 || pickupTime < 6) { cost += nightSurcharge; } return cost; }; </script> </head> <body> <form> <input type="text" onclick="taxiFare()" value="Call function"> <input type="Submit" value="OK" onclick="taxiFare()"> <input type="reset" value="Clear"> </form> <script type="text/javascript"> document.write("Your taxi fare is ₹" + taxiFare(5,2)); </script> </body> </html> pls it would be of great help. Thanx. Let's say I'm defining an object and I want the constructor to take one input and ten save it. I'd like to do something like this: function apple(color) { this.color = arguments.color; } But of course that doesn't work because arguments isn't a scope. My question is, is there a scope I can use. What I've been doing instead is this: function apple(new_color) {this.color = new_color;} But that just seems less than perfectly pretty. Hope you can help. I'm currently building a website and trying to integrate a javascript image 'tranisition' effect into mm_swapimage and failing. My knowledge of Javascipt is limited but without knowing the 'arguments' for mm_swapimage, it's impossible (looks similar to vb, but can't find an answer anywhere) I want the effect to work on a 'timed' event rather than 'OnMouseOver' so have added script to change that (which is probably the issue!) I can get both to work idependantly but not together. I've simplified the page and pasted the code below, as it stands the 'effect' works, but it only uses the primary image, not the other image in the array. I'm using DW CS4 and the transition extension is called FlevOOware. Thanks Michael 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>Untitled Document</title> <script type="text/javascript"> <!-- function MM_findObj(n, d) { //v4.01 var p,i,x; if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) { d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);} if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n]; for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); if(!x && d.getElementById) x=d.getElementById(n); return x; } function MM_preloadImages() { //v3.0 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array(); var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++) if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}} } function flvFSTI4(){//v1.01 this.style.filter="";} function flvFSTI3(v1,v2){//v1.01 var v3;if (v1.filters[0]&&v1.filters[0].status==2){v1.filters[0].Stop();}if (v2==0){v3="blendTrans(Duration="+v1.STI8+")";}else {v3="revealTrans(Duration="+v1.STI8+",Transition="+(v2-1)+")";}v1.style.filter=v3;} // Wipe Right Out function flvFSTI2(){//v1.01 var v1,v2=document,v3=v2.STI4,v4;for (v4=0;v3&&v4<v3.length&&(v1=v3[v4])&&v1.STI5;v4++){if (v1.filters&&!v2.STI7){flvFSTI3(v1,v1.STI3);v1.filters[0].Apply();}v1.src=v1.STI5;if (v1.filters&&!v2.STI7){v1.filters[0].Play();}}} // Wipe Right In function flvFSTI1(){//v1.01 // Copyright 2003, Marja Ribbers-de Vroed, FlevOOware (www.STI1.nl/dreamweaver/) var v1=arguments,v2=document,v3;v2.STI4=new Array();v2.STI7=(navigator.userAgent.toLowerCase().indexOf("mac")!=-1);for (var v4=0;v4<v1.length-2;v4+=5){v3=MM_findObj(v1[v4]);if (v3){v3.STI5=v3.src;v3.STI6=v1[v4+1];v3.STI2=v1[v4+2];v3.STI3=v1[v4+3];v3.STI8=v1[v4+4];v2.STI4[v2.STI4.length]=v3;if (v3.filters&&!v2.STI7){flvFSTI3(v3,v3.STI2);v3.onfilterchange=flvFSTI4;v3.filters[0].Apply();}v3.src=v3.STI6;if (v3.filters&&!v2.STI7){v3.filters[0].Play();}}}} function MM_swapImgRestore() { //v3.0 var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc; } function MM_swapImage() { //v3.0 var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3) if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];} } // Comma separated list of images to rotate var imgs = new Array('images/DSCN1209.jpg','images/DSCN1210.jpg'); // delay in milliseconds between image swaps 1000 = 1 second var delay = 5000; var counter = 0; function preloadImgs(){ for(var i=0;i<imgs.length;i++){ MM_preloadImages(imgs[i]); } } function randomImages(){ if(counter == (imgs.length)){ counter = 0; } MM_swapImage (flvFSTI1('slider', '',7,7,1,1, imgs[counter++])); setTimeout('randomImages()', delay); MM_swapImgRestore (flvFSTI2('slider', '')); } //--> </script> </head> <body onload="preloadImgs();randomImages();"> <img src="images/DSCN1209.jpg" name="slider" width="500" height="322" id="Image1"/> </body> </html> 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... I have a project that uses and Ajax call but it appears that the call back function cannot take arguments, nor return values. However, I have wrapped another function inside the call back function that takes xmlhttp.responseText as the argument and returns values that are supposed to be placed in a global array. If I do, for instance: callback function code.... globalArray = someFunction(xmlhttp.responseText) alert(globalArray), I get the expected values. but a function is called later to query the contents of the global array the global array is empty (No other code or functions exist in this project to alter the global array) Primary dev client is FireFox 3x on Mac OSX Is this a bug, or is there some other aspect of javascript that I need to know about? I am using ajax here because javascript does not have an array shuffling function and php does. So I send an array to the server, have it shuffled by the server and returned to the requesting page. Can anyone put into "simple" words the purpose of arguments in JS please?
Hello, I need your help. I have the following drop-down box as an example: [== FRUITS ==] apples oranges pairs kiwi lemon How can I use the code below to set the value of the drop down without knowing its value number (3)? document.getElementById('BOX1').value = 'pairs' Much thanks and appreciation for everyones help. Cheers, J I cannot get the cookie to save, I'm pretty new at web designing in general. If you could, the name of the cookie be cirulcook, also any advice you would have for me would be great! Code: <script><!-- function SETcookie(){ document.cookie="Selected="+document.getElementById('myList').selectedIndex; } function GETcookie(){ if (document.cookie){ eval(document.cookie); document.getElementById('myList').selectedIndex=Selected; }}// --></script> </head> <body onLoad="GETcookie()"> <select id="myList" onChange="SETcookie()"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> </select> Hi and hope someone can help. I'm setting up a fictitious shopping page which uses cookies to remember what a user has selected. The products are photographs that the user can select either framed or unframed versions and I'm trying to put a confirmation box if the user actually requests framed and unframed versions of the same photograph. The code I'm using actually worked before I tried to add this extra functionality but I can't work out how to test for this extra bit. Here's my code and it sets cookies with names as either lulworth01 for the unframed version or lulworth01f for the framed version. The bits that work are in black and my extra code for this test is in red. Any help would be appreciated. Thanks Rog Code: function getCookie(name) { var index = cart.indexOf(name + "="); if(index == -1) return null; index = cart.indexOf("=", index) +1; var endstr = cart.indexOf(";",index); if (endstr == -1) endstr = cart.length; return unescape(cart.substring(index, endstr)); } function setCookie(name) { if ((name.charAt(name.length-1)='f') && (getCookie(name.substring(0,10))!=null)) { confirm("You seem to have placed orders for both a mounted and framed image of the same photograph.\n\nIs that OK?"); } else { alert("Thank you.\n\nYour basket has been updated."); x=parseInt(getCookie(name)) || 0; y=x+1; var today = new Date(); var expiry = new Date(today.getTime()+28*24*60*60*1000); // plus 28 days document.cookie=name+"="+y+";expires="+expiry.toGMTString(); cart = document.cookie; } } Hi and hope someone can help, I'm reading a book on Javascript and I've been doing their tutorial on getting and setting cookies. Trouble is my code, and their supplied sample, don't work. It is supposed to display a very simple page with an image. When you click the image it is supposed to open up a new (very simple) page. Your help resolving this is greatly appreciated. My thanks, R Code follows... Code: <html> <head> <title>main page</title> <script language=JavaScript> var lastUpdated = new Date("Tue, 28 Dec 2010"); function getCookieValue(cookieName) { var cookieValue = document.cookie; var cookieStartsAt = cookieValue.indexOf(" " + cookieName + "="); if (cookieStartsAt == -1) { cookieStartsAt = cookieValue.indexOf(cookieName + "="); } if (cookieStartsAt == -1) { cookieValue = null; } else { cookieStartsAt = cookieValue.indexOf("=", cookieStartsAt) + 1; var cookieEndsAt = cookieValue.indexOf(";", cookieStartsAt); if (cookieEndsAt == -1) { cookieEndsAt = cookieValue.length; } cookieValue = unescape(cookieValue.substring(cookieStartsAt,cookieEndsAt)); } return cookieValue; } function setCookie(cookieName, cookieValue, cookiePath, cookieExpires) { cookieValue = escape(cookieValue); if (cookieExpires == "") { var nowDate = new Date(); nowDate.setMonth(nowDate.getMonth() + 6); cookieExpires = nowDate.toGMTString(); } if (cookiePath != "") { cookiePath = ";Path=" + cookiePath; } document.cookie = cookieName + "=" + cookieValue + ";expires=" + cookieExpires + cookiePath; } </script> </head> <body> <h2 align=center> Welcome to my website </h2> <br><br> <center> <script> var lastVisit = getCookieValue("Last Visit"); if (lastVisit != null) { lastVisit = new Date(lastVisit); if (lastVisit < lastUpdated) { document.write("<a href=\"WhatsNew.htm\">"); document.write("<img src=\"new.jpg\" border=0></a>"); } } var nowDate = new Date(); setCookie("LastVisit", nowDate.toGMTString(),"","") </script> </center> </body> </html> Alright well Hello, I currently have a table that shows a background image and I have 1 TD with 100% width and height and in that TD I have a DIV that moves by margin-left and margin-top via JavaScript and the height is approx 20px by 20px, so basically I have a map with a character that moves when keys are pressed. My problem is I'm having trouble setting limits (where the character cannot go inside the TD). etc if it reachs a X and Y then it would stop, but it's not that easy, I currently have this in a IF function when the keys are pressed: Code: var x; var y; var exclude = { x: [50, 50, 50, 50, 50], y: [50, 60, 70, 80, 90] }; if (exclude.x.indexOf(x) !== -1 && exclude.y.indexOf(y) !== -1){ // dismiss } else { //run main code.. } But that code doesn' work correctly because I want the numbers in exclude.x to match the oppisite of exclude.y so 50 and 50, 50 and 60 but instead its like this 50 and 50 or 60 or 70 or 80 or 90. I just want it to be set so it matches the number... Code: x: [1, 2, 3, 4, 5], y: [1, 2, 3, 4, 5] Hope you can help I've been having trouble for awhile now, thanks. What I'm trying to do is to do something similar to what this person wanted on their question: http://www.webmasterworld.com/javascript/3338586.htm I already have it so when the user clicks on one of the links, then it changes to the active class. But now I would like to have the first link already have the active class (which is the effect the links will have when the user clicks on it) and then have the same effect happen thereafter the user clicks on the links. Here is the Javascript: Code: <script type="text/javascript"> var hrefs=document.getElementsByTagName("a"); var hrefs=document.getElementsByClassName("links"); var preA=""; for(var i=0;i<hrefs.length;i++){ hrefs[i].onclick=function(){ if(preA!="" && preA!=this){ preA.className="links"; } this.className="active"; preA=this; } } </script> Here is the CSS: Code: a.links:link { color: #FFF; text-decoration: none; } a.links:hover { color: #96C; text-decoration: none; } a.active { color: #96C; text-decoration: none; } Here is the HTML: Code: <a class="links" href="#">Curriculum Vitae</a> | <a class="links" href="#">Teaching Philosophy</a> | <a class="links" href="#">Artist Statement</a> Hi Guys , This is the urgnt requirement , I want to change the Browsers setting languge through java script ,and according to it , The data wht I enter dhould be change .Thanks In advance Hi All, I would like to enable / disable my field validation based upon the status of a given checkbox in my form but I am unsure about how to "unset" the varibles that control the validation. If the user clicks the checkbox, this displays the fields ant enables my validation just fine. But if the user then unckeck the box, the field is hidden but the validation remains enabled and the form cannot be submitted. Here is my code: Code: if (document.getElementById("OnAirVariance").checked) { var sprytextfield3 = new Spry.Widget.ValidationTextField("spryStartTime", "time", {validateOn:["blur"], format:"HH:mm:ss", useCharacterMasking:true}); var sprytextfield4 = new Spry.Widget.ValidationTextField("spryEndTime", "time", {format:"HH:mm:ss", useCharacterMasking:true, validateOn:["blur"]}); var sprytextfield5 = new Spry.Widget.ValidationTextField("spryMaterialID", "none", {validateOn:["blur"]}); var sprytextfield6 = new Spry.Widget.ValidationTextField("spryTitle", "none", {validateOn:["blur"]}); }else{ I NEED TO BE ABLE TO REVERSE THE SET VARIABLES SO THE VALIDATION WILL NOT STAY IN EFFCT } Thanks in advance for any help. Kind regards, Ken |