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.


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 :slight_smile: but all the problems occur in the myReserve function just above. Everything else works fine.


<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>

The problem lies here:


for (var j=0; j<arrayLength; j++)
{
  str = customerList[j]
}

document.getElementById("Movie_List").innerHTML = str

Every time in the loop you replace the value of the str variable, while you shoud be appending to it.

The correct way would be


for (var j=0; j<arrayLength; j++)
{
  str += customerList[j] + "<br />";
}

document.getElementById("Movie_List").innerHTML = str

OR, another way, which is more neat:


str = customerList.join("<br />");
document.getElementById("Movie_List").innerHTML = str

I would also like to suggest you use javascript object to store all movie related information in one array instead of three seperate arrays. While three seperate arrays are syntactically correct, using objects is more semantically correct.

You would get something like the following:


var movies = new Array(
{name: "Movie 1", image: "movie1image.jpg", description: "Movie 1 description"},
{name: "Movie 2", image: "movie2image.jpg", description: "Movie 2 description"}
);

Now you can access movie 1’s image by calling movies[0].image and it’s description by movies[0].description, etc.

Take care that arrays start at index 0, not index 1. Meaning the first movie is movies[0], the second movie is movies[1], etc.

^ hey thanks for your reply…

The first way you suggested doesn’t work, I can’t see why though.

The second way works like a charm though. Now I will add an IF statement to stop the same movie being added twice.

I have another question… I want to place a link after each movie statement “delete” … that will call a function… the function should remove the selected item from the array.

I’m not sure where to start with this though.

Take a look at the splice() function.
You can use this function to remove items from arrays :slight_smile:

Thanks, I have never came across that function. Could I also use it for moving items within the array? Or is there another method for moving items within an array?

I have been trying to get an IF statement working that will stop duplicate entries in my array but I can’t get an output at all now.

As far as I know there is no method to move items within arrays.
You’ll have to figure something out using the slice() function.
Why do you want to move items in an array? Isn’t there are better way to do it?

Could you post the code with your IF statement so we can have a look what’s going on?

This page includes information on adding and removing elements to the middle of an array.

Manipulating JavaScript Arrays