JavaScript - Manipulating Arrays.... Help !!
OK first of all I will post some screenshots of the 'website' I have created so far and explain what is working and what is not working. Then I will post my code and ask for help.
Below is the main screen before any action happens. The three boxes are DIV elements. The writing and dropdown menu in the first box is generated by Javascript code. Whenever a user selects an option from the dropdown menu. Information about the movie and a picture of the cover are displayed. The movie title, picture filename and movie description are all stored in three separate arrays. Now for the problem. I have created a fourth array "customerList" and left it empty. Whenever a customer clicks the reserve button it calls a function "myReserve()". This function takes the selection from the dropdown menu, then uses the push function to add the selection to the blank array. I then use the code "arrayLength = customerList.length" to get the length of the customer list. A for loop is used to cycle through the array and display the contents of the array. The problem is it only displays one selection. When reserve is clicked again the newest selection is displayed. Why will it not push the next item into the array? Javascript code, just skip through the 3 arrays at the top... the problem function is at the bottom. Code: var movieTitles = new Array(8) movieTitles[0] = "The Prestige [2006]" movieTitles[1] = "The Lives of Others [2007]" movieTitles[2] = "The Bourne Ultimatum [2007]" movieTitles[3] = "Spider-Man 3 [2007]" movieTitles[4] = "Casino Royale [2006]" movieTitles[5] = "The Illusionist [2006]" movieTitles[6] = "Sunshine [2007]" movieTitles[7] = "Zodiac [2007]" movieTitles[8] = "Quantum of Solace [2008]" var movieCovers = new Array(8) movieCovers[0] = "prestige.jpg" movieCovers[1] = "lives_of_others.jpg" movieCovers[2] = "bourne3.jpg" movieCovers[3] = "spiderman3.jpg" movieCovers[4] = "casinoroyal.jpg" movieCovers[5] = "illusionist.jpg" movieCovers[6] = "sunshine.jpg" movieCovers[7] = "zodiac.jpg" movieCovers[8] = "quantum_of_solace.jpg" var movieDescriptions = new Array(8) movieDescriptions[0] = "Two Victorian-era magicians develop a rivalry that builds into an escalating battle of tricks." movieDescriptions[1] = "Five years before its downfall, the former East-German government ensured its claim to power with a ruthless system of control and surveillance." movieDescriptions[2] = "Legendary assassin Jason Bourne uncovers mysteries of his past, which puts him in the cross-hairs of a superkiller." movieDescriptions[3] = "When Peter Parker's suit suddenly turns black it brings out the dark, vengeful side of his personality." movieDescriptions[4] = "The story examines James Bond's first mission after getting his licence to kill." movieDescriptions[5] = "Eisenheim is a stage magician who amazes the audiences of turn-of-the-century Vienna, drawing the attention of Crown Prince Leopold." movieDescriptions[6] = "Fifty years from now, the sun is dying, and mankind is dying with it. Our last hope: a spaceship carrying a device which will breathe new life into the star." movieDescriptions[7] = "A serial killer terrifies the San Francisco Bay Area and taunts police with his ciphers and letters." movieDescriptions[8] = "Seeking revenge for the death of his love, secret agent James Bond sets out to stop an environmentalist from taking control of a country's water supply." var customerList = new Array() function getMovieTitle() { var str = "<p>Available movies are contained in the list below.<br />Select a movie title to read more details.<br />If you want to add the movie to your list click the reserve option.<br /></p>" str = str + "<form action='P4_1.html' method='post'><select onChange = 'displayMovie()' name='title' id = 'droplist'><option>Choose a movie</option>" mylength = movieTitles.length //loop for each movie title in the movieTitles array for (var i=0; i<mylength; i++) { str = str + "<option>" + movieTitles[i] + "</option>" } str = str+"</select></form>" //place content into dropdown menu document.getElementById("dropdown").innerHTML = str } function displayMovie() { var i i = document.getElementById('droplist').selectedIndex - 1 var m = movieTitles[i] m = m + "<p><br><img src='"+movieCovers[i]+"'></p>" m = m + movieDescriptions[i] m = m + "<p> <a href='Javascript:myReserve()'><span id = 'res'> Reserve </span></a></p>" document.getElementById("Movie_Info").innerHTML = m } function myReserve() { var i i = document.getElementById('droplist').selectedIndex - 1 customerList.push(movieTitles[i]) arrayLength = customerList.length for (var j=0; j<arrayLength; j++) { str = customerList[j] } document.getElementById("Movie_List").innerHTML = str } HTML code, incase you want to create my files yourself to troubleshoot for me but all the problems occur in the myReserve function just above. Everything else works fine. Code: <html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882"> <head> <title>P4_1</title> <script src="P4.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" media="screen" href="P4.css" /> <!--[if gte mso 9]><xml> <mso:CustomDocumentProperties> <mso:ContentType msdt:dt="string">Document</mso:ContentType> </mso:CustomDocumentProperties> </xml><![endif]--> </head> <body onload="javascript:getMovieTitle()"> <img src="logo.jpg"> <div id="dropdown" class="box1"> </div> <div id="Movie_Info" class="box2"> <p>Movie info will go here</p> </div> <div id="Movie_List" class="box3"> <p>Your movie list will go here</p> </div> </body> </html> Similar TutorialsHello, Here is my situation. I have a java array generated from a JSP on the server side, and saved in the session. This array consists of objects (of say class X). How can I load this array into a javascript array so I can search for a this array based on attributes of the object? Thanks Is the hiding/showing of text fields done differently than for buttons? I ask because I have the following text field: Code: <input type="text" name="case_id_c" class="sqsEnabled" tabindex="0" id="case_id_c" size="" value="" > And if I call the following javascript, this field disappears: Code: document.getElementById('case_id_c').style.display = 'none'; However, I have the following button: Code: <input type="button" name="btn_clr_case_id_c" tabindex="0" title="Clear [Alt+C]" accessKey="C" class="button" onclick="this.form.case_id_c.value = ''; value="Clear"> And if I run the following code, nothing happens: Code: document.getElementsByName("btn_clr_case_id_c").style.display = 'none'; Not sure what's going on. Any thoughts??? Hello, I came across a very odd browser behavior when trying to modify a css class using javascript and at the same time having a base html statement in my html file. Without the base html statement, all browsers work fine and I can change the css class definition using javascript easily. With a base html statement, only FireFox still works while Internet Explorer and Google Chrome dont work anymore. If there is a cross-domain issue, while one browser does work and the others dont? An example of what I'm talking about, with the base statement: http://freebsdcluster.org/~casaschi/...mple-base.html Without the base statement: http://freebsdcluster.org/~casaschi/...le-nobase.html Any idea how to tweak the code in the case with the base html statement in order for the javascript to work with all browser (modifying the class definition) ??? Keep in mind, I dont want a suggestion of another way to change the color, this is only an example. I want to be able to manipulare css classes with javascript when a base html statement is in my html code. This is essentially the code: Code: <!-- --> <base href='http://www.google.com'> <style id='myStyle' type='text/css'> .myStyle { color: red; } </style> <script type="text/javascript"> var lastColor = 'red'; function toggleColor() { lastColor = lastColor == 'red' ? 'green' : 'red'; myObject = document.getElementById('myStyle'); if (myObject.sheet) { myObject.sheet.cssRules[0].style.color = lastColor; } // Mozilla style if (myObject.styleSheet) { myObject.styleSheet.rules[0].style.color = lastColor; } // IE style } </script> <a href="javascript: toggleColor();"><span class=myStyle>click here to toggle color</span></a> Thanks in advance... I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* Code: <HTML> <HEAD> <TITLE>Listing 4.4</TITLE> <SCRIPT TYPE="text/javascript"> //DEFINE METHOD function displayInfo() { document.write("<H1>Employee Profile: " + this.data[0] + "</H1><HR /><PRE>"); document.writeln("Employee Number: " + this.data[1]); document.writeln("Social Security Number: " + this.data[2]); document.writeln("Annual Salary: " + this.data[3]); document.write("</PRE>"); } //DEFINE METHOD TO GET EMPLOYEE INFORMATION function getInfo() { var menu="0-Exit/1-Name/2-Emp. #/3-Soc. Sec. #/4-Salary"; var choice=prompt(menu,"0"); if (choice != null) { if ((choice < 0) || (choice > 4)) { alert ("Invalid choice"); this.getInfo(); } else { if (choice != "0") { this.data[choice-1]=prompt("Enter information",""); this.getInfo(); } } } } //DEFINE OBJECT function employee() { this.data = new Array(4); this.displayInfo=displayInfo; this.getInfo=getInfo; } newEmployee=new employee(); </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/javascript"> newEmployee.getInfo(); newEmployee.displayInfo(); </SCRIPT> </BODY> </HTML> I am currently taking a Javascript certification course, this is a exercise given (final code) I don't completely understand what is going on though, could someone explain to me Code: this.data[choice-1]=prompt("Enter information",""); that part? I don't understand why, [choice-1] I don't fully understand why an array is even needed here? First of all thank you for reading my thread and giving time to help me. Here goes my question: How to sort this array? MY PRIORITY COLORS array: ------------ green , yellow ALL COLORS array : <---- this will be your main array. ----------------------- pink , green , orange THE RESULTS: ( the results after you sort) (Not sorted by alphabetically, but sorted by the priority colors) ---------------- green , pink , orange I hope you could help me solve this javascript sorting problem. Thank you! Hi could someone help with this javascript. i dont know where to start with the script which is in bold. Program to report the results of an election. // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; // total votes -- to be initialised below var totalVotesArray; // Add code to // -- initialise totalVotesArray with a new empty array of the same size as candidateArray // -- use a for loop to add the online and paper votes for each candidate and store the result at the corresponding position in the total votes array. Hi. I am fairly new to JavaScript. I am having some troubles with arrays. I am using Chrome 12 beta. Here is a brief version of the code I am having trouble with Code: var array=new Array() array[0]=new Array() array[0][1]=new Array() var array[0][1]=[ 3, 1, 4, 1, 5, 9, 2, 6, 5, ... ]; I do not want to use "array[0][1][n]" because my array has too many items to do that and it is just plain annoying to change the numbers that way. I get an error on the "var buffers[0][1]=[" line saying: "Uncaught SyntaxError: Unexpected token [" What is the problem in my code? Thank you ahead of time. ---mint I am working on making 2 for loops of 2 arrays to get the total of them. Then I need to get the average heights. This is for a test, yet I have not got a clue, so I need clues as I cant get it to work and I am a new coder to javascript. Code: var heights = [15,16,17,18,19]; var numbers = [2,1,6,4,2]; var average = new Array(5); average = 0 for (var heights = 0; heights <= 5; heights = heights+ 1) { total = 0 } for (var numbers = 0; numbers <= 5; numbers = numbers + 1) { total = 0 average = heights / numbers; } document.write('The average height is ' + average); Am I on the right road? I need to use this format and not functions. I have got 2 for statements but maybe I could do this with one, it is so tricky this javascript. Hi, new to this forum but have a quick question about arrays, I've been working on this all night, and I'm at a loss. I'm trying to calculate the gpa of a user by using arrays and functions. Everything seems to be working besides two things.
The array that contains the class names (className[]) always includes an extra two variables: my sentinel value which is finish, and "undefined"
The arrays at the end won't produce a number when multiplied together. creditData[] and qualityPoints[].
Also, if you have any suggestions on my code, I'd appreciate it. <script type="text/javascript"> <!-- /**************************************************************** ** PrintExplanation - prints a message containing instructions to the user without ** any variable needed. ** Inputs:None ** Outputs:None ****************************************************************/ function PrintExplanation() { alert("This program will calculate your Grade Point Average for any given semester. Please enter only graded classes, no Pass/Fail Classes."); } /**************************************************************** ** GetValidNumberInput - Error checks a number between two constraints. ** Inputs: promptString - allows the user to insert a string in order to be asked. ** lowerNum - the lower constraint you want to be compared. ** upperNum - the higher constraint you want to be compared. ** Outputs: numCredits ****************************************************************/ function GetValidNumberInput(promptString, lowerNum, upperNum) { var promptString; var lowerNum; var upperNum; var numCredits; numCredits=prompt(promptString); while(numCredits<lowerNum || numCredits>upperNum) { numCredits=prompt(promptString); } numCredits=parseFloat(numCredits) return numCredits } /**************************************************************** ** CalculateGPA - Calculates the users GPA ** Inputs: totalCredits: The total amount of credits determined by the user. ** totalQualityPoints: The total amount of quality points determined by the user. ** Outputs: gpa - the users final grade point average. ****************************************************************/ function CalculateGPA(totalCredits, totalQualityPoints) { var totalCredits; var totalQualityPoints; var gpa; gpa=totalQualityPoints/totalCredits return gpa; } function GenerateGPAReport(totalCredits, totalQualityPoints) { } /**************************************************************** ** ConvertGradeToPoints - Converts a letter given by the user into a number corresponding to grade points. ** Inputs: grade - the letter of the grade the student recieved in the course. ** Outputs: points - the number value of the grade that was input by the user. ****************************************************************/ function ConvertGradeToPoints(grade) { var grade; var points; if(grade == "A" || grade== "a") { points=4 } else if(grade == "B" || grade == "b") { points=3 } else if(grade == "C" || grade == "c") { points=2 } else if(grade == "D" || grade == "d") { points=1 } else if(grade == "F" || grade == "f") { points=0 } points=parseFloat(points); return points; } //--> </script> </head> <body> <script type="text/javascript"> var promptString; /*Declares Variables*/ var className; var numOfClasses; var grade; var semester; var numCredits; var lowerNum=1; var upperNum=4; var class1; var i=0; var counter=0; var totalCredits=0; var totalPoints=0; var grade; var counterCredits=0; var counterGrade=0; var points; var gpa; var qualityPoints; var creditData; var gradeData; var x=0; var totalQualityPoints=0; PrintExplanation(); var className = new Array(i); semester=prompt("Please enter the semester you would like to calculate your GPA for."); document.write("Grade report for " + semester + "<br />"); while(class1!="finish") /*Stores the names of the classes taken into an array*/ { class1=prompt("Enter the Class name, or finish to end"); className[i]=class1 i++ } while(counter<=i) /*writes the classes in the array from top to bottom*/ { document.write(className[counter] + "<br />"); counter++ } var creditData = new Array(i) while(counterCredits<=i) /*counts the total number of credits for all the classes*/ { numCredits=GetValidNumberInput("How many credits is " + className[counterCredits] + " class worth?",1,4) creditData[counterCredits]=numCredits totalCredits=totalCredits + numCredits counterCredits++ totalCredits=parseFloat(totalCredits); } var gradeData = new Array(i) /*collects information about grades in an array*/ while(counterGrade<i=) { points=prompt("What grade did you recieve in " + className[counterGrade] + "?"); points=ConvertGradeToPoints(points) gradeData[counterCredits]=points totalPoints=totalPoints+points counterGrade++ } while(x<=i) { qualityPoints=creditData[x]*gradeData[x] totalQualityPoints=totalQualityPoints + qualityPoints x++ } gpa=CalculateGPA(totalCredits, qualityPoints) document.write(gpa); </script> </body> I have a quick question with multiple array and random numbers. If i generate my random numbers in one array, how would i take a selection of those numbers and put them in another array? Ex: array 1: 25, 34, 38, 40, 22, 49 want to move numbers between 30 and 50 to another array. array 2: 34, 38, 40, 49 is it as simple as for loops and if statements setting the conditions? do i use a sorting method? (selection? bubble?) any help would be appreciated. is it possible to embed something like this Code: <object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' width='450' height='24'> <param name='movie' value='http://youtubemp3.tv/player/player.swf'> <param name='allowfullscreen' value='false'> <param name='allowscriptaccess' value='always'> <param name='wmode' value='transparent'> <param name='flashvars' value='file=http://youtubemp3.tv/mp3embed-oeduvhv516z9.mp3&duration='> <embed src='http://youtubemp3.tv/player/player.swf' width='450' height='24' allowscriptaccess='always' allowfullscreen='false' flashvars='file=http://youtubemp3.tv/mp3embed-oeduvhv516z9.mp3&duration=' /> </object> into a array that will randomly pull things from it like this Code: <input type = "button" value="Call Out a Target" onclick="myFunction()"></button> <div id = "demo1"></div> <div id = "demo2"></div> <script type="text/javascript"> function shuffle(array) { var n = array.length, k, t; if (n == 0) {return false}; while (--n) { k = Math.floor(Math.random() * (n+1)); t = array[n]; array[n] = array[k]; array[k] = t; } } function myFunction() { var myarray=["red","blue", "yellow", "orange"]; shuffle (myarray); document.getElementById("demo2").innerHTML = myarray[0]; } </script> Thanks!!! Hey, I'm working on a problem and what I need the program to do is to add up the numbers in the array NOT add up how many numbers there are. There are 5 total numbers that a user will input. The counting of the numbers will be in a seperate method which will then return to the main. Then be displayed through system.out.println. I don't know where I am going wrong any help? Thanks! Code: import javax.swing.*; import java.util.*; public class Question10 { public static void main (String []args) { //declares Scanner keyboard = new Scanner(System.in); int [] myNums = new int[5]; for (int i=0; i < myNums.length; i++) { System.out.println ("Please Enter Data"); myNums[i]= keyboard.nextInt(); } } //end main public static int getTotal(int inArray) { int a,b,c,d,e,f; f = a+b+c+d+e; return f; } }//end class Hi again folks! A code I did recently was that 10 football teams had to register and the program had to ask the question "please enter your team" ten times then show the display on screen. This code works fine and does it jobs but I realized that I did this program a long winded way (shown below) : <script type="text/javascript"> //ask to enter names var enteredteam1= prompt("Please enter first team.", ""); //each team is shown as different variable var enteredteam2= prompt("Please enter second team.", ""); var enteredteam3= prompt("Please enter third team.", ""); var enteredteam4= prompt("Please enter forth team.", ""); var enteredteam5= prompt("Please enter fifth team.", ""); var enteredteam6= prompt("Please enter sixth team.", ""); var enteredteam7= prompt("Please enter seventh team.", ""); var enteredteam8= prompt("Please enter eighth team.", ""); var enteredteam9= prompt("Please enter ninth team.", ""); var enteredteam10= prompt("Please enter final team.", ""); var team= []; team[1]= enteredteam1 //the team should equal the entered value for the space team[2]= enteredteam2 team[3]= enteredteam3 team[4]= enteredteam4 team[5]= enteredteam5 team[6]= enteredteam6 team[7]= enteredteam7 team[8]= enteredteam8 team[9]= enteredteam9 team[10]= enteredteam10 document.write("<h1>Registered Teams</h1>"); // display the teams on the screen beside number document.write("<b>1.</b>" + team[1]); //write the entered value on the screen document.write("<br><br><b>2.</b>" + team[2]); document.write("<br><br><b>3.</b>" + team[3]); document.write("<br><br><b>4.</b>" + team[4]); document.write("<br><br><b>5.</b>" + team[5]); document.write("<br><br><b>6.</b>" + team[6]); document.write("<br><br><b>7.</b>" + team[7]); document.write("<br><br><b>8.</b>" + team[8]); document.write("<br><br><b>9.</b>" + team[9]); document.write("<br><br><b>10.</b>" + team[10]); </script> I was wondering for future references could anyone suggest a simpler code to do something similar? For instance what if I wanted to ask the question but I didn't know how many teams were going to be entered. It would ask the question (enter your team) until the user clicked on a button saying "finished" or something. Once again, I am new to this field, so any code with comments would be helpful! hi i have two arrays and i need to know which strings are in both arrays. i know how to do the bit if the string is in both but i don't know how to compare them as such. thanks If anyone is planning on buying "ICAB4225B Automate Processes" in relation to a TAFE/College/School course, I suggest getting the teacher to actually READ the book before they use it. Tonight has been a HE-Double Hockeysticks (Not sure on language in this forum) of fixing mistakes the book has made. Double commars inplace of singles, singles inplace of doubles, single brackets, whole chunks of text that are wrong. In one place in the book it tells me to copy the text in blod and there is none. Anyway.... The code that the book has made me piece together over the last few questions has left me with: Code: <script type = "text/javascript"> { var counter = 0 var NoOfItems var ItemsNames = new Array() NoOfItems = prompt ("How many items do you want to hock?",""); for (NameCount=0; NameCount<NoOfItems; NameCount++) { ItemNames [NameCount] = prompt ("What are the names of your items?",""); } document.write ("<form name='myform'><br><table>"); while ( counter < NoOfItems) { document.write ("<tr><td><value>Enter the price of the " + ItemNames [count] + "</td><td><input type='text' name='" + ItemNames [count] + "'></td></tr>"); counter++ } document.write ("<tr><td><input type='submit' value='Submit Details' onClick='validateform'</td></tr></table></form>"); } </SCRIPT> The problem I am having it with the Array. I dont think that var = new Array is correct but thats what my text book is telling me. Any help? I'm a newbie of JS and don't know if I have got the right terms in my question. I want to lowercase all the arrays: Code: <script> var txt = [ ["Cats","Dogs","Rabbits"], ["Fish","Bones","Carrots"] ] document.write(txt[0][1] + " love eating " + txt[1][1]); </script> I know I can do something like this: Code: document.write(txt[0][1].toLowerCase() + " love eating " + txt[1][1].toLowerCase()); // or var txt1 = txt[0][1] + " love eating " + txt[1][1]; document.write(txt1.toLowerCase()); But if I will loop through all the arrays and print them out, I am bothered with appending .toLowerCase(0 after each array one by one, so is there any way to bind that method at one go? I hope my question is understandable. Maybe I've used wrong terms of JS. Thank you. Hi, I am trying to merge the values of 2 arrays. array 1 = 1, 2, 3, 4, 5 array 2 = a, b, c, d, e Resulting in: array 3 = 1-a, 2-b, 3-c, 4-d, 5-e etc both arrays that will be used originally will always of the same length. Both arrays will contain numbers Can you please help? Thanks |