User Tools

Site Tools


en:web_development:lists:javascript

Web Development Lesson 3 - Lists

Javascript Lists

Objectives

In this exercise you will use an array to store a list of items, use a for loop to repeat a block of code, and use an if statement to run different instructions based on user input.

Setup

  • We'll use the first file you created in this lesson called 'lists.html', so open that file in Visual Studio Code.
  • Create a file called 'lists.js' in the same directory.
  • We'll also return to jsfiddle to try out a few things.
  • We'll start with a blank slate for this, so if you have anything in the HTML, CSS or Javascript panels of jsfiddle, delete them.

External Scripts

  • We'll start in Visual Studio Code.
  • Just as we created an entry in <head> to link to the external style sheet, we need to tell the browser where to find our javascript code.
  • Create a new line in <head> and type 'script', then select 'script:src'.
  • Type the name of our javascript file 'lists.js' into the src attribute.
<script src="lists.js"></script>
  • We can now work in our javascript file and the browser will find it when we open the 'lists.html' page.

Arrays

  • An 'array' is essentially a list in code form.
  • Type the following text into 'lists.js'.
players = ['David Ospina Ramirez',
           'Johan Andres Mojica Palacio',
           'Gustavo Leonardo Cuellar Gallego',
           'Duvan Esteban Zapata Banguera'];
  • By now you should be familiar with the form of the statement. player is the name of a variable and it now holds everything after the = sign.
  • [] identifies an array, in this case holding a list of players.
  • Each of the player names is text, so we surround them with ' signs.
  • I've included names of 4 Colombian football players, but there are many more. Feel free to add any others you know using the same format.
  • I've written each of the names on a separate line to make it clear. This is good practice, but it's not essential - you can string them all on the same line as long as you separate the items with a , .

Referencing Array Elements

  • To display these items, we need to be able to reference them.
  • You've seen how to do this before. In the previous lesson, we accessed elements with specific tags using document.getElementsByTagName('span')[2]. document.getElementsByTagName('span') is an array (a list) of all elements with the tag span. [2] means that we access the 3rd item in the list. Remember that the first item is [0] .
  • We can see this more easily in jsfiddle.
  • Create a simple array in the Javascript panel as follows.
cars = ['Ferrari', 'Porsche', 'Lamborghini'];
  • Here, the array is simple enough that I've left it on a single line.
  • Now, let's display the first element in the list on our page.
document.body.innerHTML = cars[0];
  • Run the code and see that it displays 'ferrari', the first item.
  • Try changing the number inside the [] and check the results to be sure you understand how it works.
  • Using this technique, we can display the results of our list in our Visual Studio page.
  • Open 'lists.html' and add an unordered list just before the closing </body> tag.
  <h2>Players</h2>
  <ol></ol>
</body>
  • We'll use this to display our Javascript array.
  • After the players list in 'lists.js', add the following code to generate our list code.
playerList = "";
playerList += "<li>" + players[0] + "</li>";
playerList += "<li>" + players[1] + "</li>";
playerList += "<li>" + players[2] + "</li>";
playerList += "<li>" + players[3] + "</li>";
  • Can you see how this works? We're building a string with all our list items, one on each line. Each has the opening and closing list ags with the list item in between.
  • Next we need to display the string we've created.
document.getElementsByTagName('ol')[2].innerHTML = playerList;
  • This looks for the 3rd <ol> tag and inserts the list string there.
  • If you run the code now, it probably won't work because the Javascript code executes before the HTML code has finished loading (ie the 3rd <ol> tag doesn't exist when the code runs). To avoid this, we need to wrap the display command inside a function that only runs when the page is fully loaded.
window.onload = function() {
  document.getElementsByTagName('ol')[2].innerHTML = playerList;
}
  • window, like document identifies the whole page.
  • .onload triggers when the HTML code has finished loading.
  • When this is true, the browser will run the function containing all the code between {} .
  • You don't need to remember or understand all this completely, but you should be able to recognise this pattern and be able to apply it when necessary. We'll use it often during the course so you become familiar with it.
  • The code should work now when you run it, but if you've added all 16 players, listing them all would take more work. And some lists (like the list of products on MercadoLibre) have thousands of entries.
  • We can save ourselves a lot of time by writing a 'for loop' that will run through all entries and create the string dynamically.

For Loops

  • The name ‘for loop’ will seem strange if you’re new to programming. It essentially means that ‘for’ each item in the list, we will ‘loop’ through a given block of code. ie. we’re going to apply the same code (add the item to our string) to every player.
  • Let’s go back to jsfiddle to see how this works.
  • Type the following code into the Javascript section below the cars array.
for (i = 0; i < 10; i++) {
}
  • for is the function, which will run code inside the {} a number of times according to the rules inside () .
  • The rules are in 3 parts - starting condition, continuing condition, and changes made each time, all separated by ; .
  • For each of these, by convention, we'll use a variable i , short for 'iterator'.
  • i = 0 means that the first time we run the code, the variable i will have a value of zero.
  • We'll run the code as long as i < 10 is true.
  • Finally, i++ is the same as i = i + 1 so each time we loop through the code, we'll increment the variable i . So it will run with a value of i incrementing from 0 to 9.
  • Let's see this in action by adding an 'alert' to display the value of i .
  • Add the following code between the {} .
alert("i = " + i);
  • When you run the code, you should see a series of popups displaying the value of i .
  • Comment that out with // .
  • Now, lets write it on our page directly. Add the following code inside {} .
	text += i + "<br />";
	document.body.innerHTML = text;
  • Can you work this out?
  • text is a variable we'll use to hold the text to be displayed.
  • += means that we'll add the new text to the full string we're building.
  • The new string is the variable i and a <br> tag which adds a new line.
  • document.body.innerHTML refers to the entire content (body) of the HTML document.
  • We'll assign string we've built (text) to the HTML body.
  • There's one problem with this and if you run it you won't see anything yet.
  • Our browser doesn't know what text is the first time it sees it.
  • Add the following code at the top of the Javascript section (before the for loop).
var text = "";
  • Here we are telling the browser that text is a variable (var of type String ( "" ).
  • Now run the code and see the list of numbers from 0 to 9.

Iterating Arrays

  • So now that you understand how for loops work, we can apply it to an array.
  • Open your jsfiddle tab again.
  • Let's edit the for loop you have already.
var text = "";
for (i = 0; i < 10; i++) {
	text += cars[i] + "<br />";
}
document.body.innerHTML = text;
  • To differentiate the two lists, let's change the name of the new list to carList.
var carList = "";
for (i = 0; i < 10; i++) {
	carList += cars[i] + "<br />";
}
document.body.innerHTML = carList;
  • In the for loop, the starting condition i = 0 and iterating statement i++ are still valid, but we need to adjust the continuing condition to stop at 3 items.
var carList = "";
for (i = 0; i < 3; i++) {
  carList += cars[i] + "<br />";
}
document.body.innerHTML = carList;
  • If you run his now, it should show all 3 cars, one on each line.
  • Now have a go at applying this yourself to the list of players in Visual Studio Code.
  • Here's my version.
players = ['David Ospina Ramirez',
           'Johan Andres Mojica Palacio',
           'Gustavo Leonardo Cuellar Gallego',
           'Duvan Esteban Zapata Banguera'];

window.onload = function () {
  playerList = "";
  for (i = 0; i < 4; i++) {
    playerList += "<li>" + players[i] + "</li>";
  }
  document.getElementsByTagName('ol')[2].innerHTML = playerList;
}
  • Did you have something similar?
  • If you added more players, you won't be using the number 4. Or if you did, you won't see the whole list.
  • In fact, if you pull a list from a database, which we'll do much later in the course, you likely won't know how many items are in the ilst. What do you do then?
  • Thankfully, Javascript can count the number items in an array for you using .length .
  • Let's see how this works in jsfiddle.
  • Add an alert to your Javascript code.
alert("cars has " + cars.length + " items.");
  • Run that and check that it does what you think it should.
  • So we can change our continuing condition for the list of players as follows.
for(i = 0; i < players.length; i++) {
  • Run it now and see that it shows exactly as many players as you have in your list.
  • Congratulations on creating a list using Javascript.

Conditional Statements

  • Sometimes the action you take will depend on some other factor - user input, previous actions or information from a database for example.
  • The simplest of these is the 'if statement'.
  • Let's jump back to jsfiddle to see how this works. Delete all the Javascript you have there at the moment.
  • Enter the following code into the Javascript panel.
var x = 2;
if (x == 2) {
	alert 'the condition is true';
}
  • The basic structure of this code is if (condition) { code to execute if true }.
  • We have a condition inside the () , and only if that condition is true do we run the code inside {} .
  • In this case, our condition is x == 2 , which checks the value of x and the value of 2 . If the value of x is 2, then it will run the code displaying an alert.
  • Since we've just defined x = 2 (first line), this condition is true and the alert will be displayed. Try it now.
  • Now change the value of x to 5 (or anything but 2) and run the code again.
  • Nothing is displayed. Let's add a message if it fails too.
var x = 2;
if (x == 2) {
	alert 'the condition is true';
} else {
	alert 'the condition is false';
}
  • Here, we have added else with code that will run if the condition is not met. Run the code again with the wrong value of x and see the new statement.
  • Now, let's apply that to our checklist in 'lists.html' using Visual Studio Code.
  • If the user checks a checkbox, we will make the associated text grey. If they uncheck it, we'll make the text black again.
  • Add an attribute to each of the list items to call a Javascript function.
        <li><input type="checkbox" name="flour" onchange="toggleCheckbox('flour')">100g flour</li>
        <li><input type="checkbox" name="eggs" onchange="toggleCheckbox('eggs')">2 eggs</li>
        <li><input type="checkbox" name="milk" onchange="toggleCheckbox('milk')">300ml milk</li>
  • onchange="" will trigger whenever there is a change to the element - in this case when the checkbox is checked or unchecked. When triggered it will run the Javascript code between the "".
  • We will call our Javascript function 'toggleCheckbox' and pass the function the name of the checkbox element so the function will know which line to update.
  • Now, save 'lists.html' and open 'lists.js'.
  • Add our function below the existing code.
function toggleCheckbox(item) {
}
  • First we define the code as a 'function' using function which means it will only run when specifically called. In this case we'll call it by clicking the checkbox, but it could also be called from other code.
  • Next, we name the function 'toggleCheckbox'.
  • Then we assign the information passed by the onChange attribute (the name of the checkbox) to the variable called item.
  • Finally, we have {} ready to contain our code to be run.
  • To make things a bit easier, we'll find the actual checkbox using the name, and assign that to a variable. Copy the following code inside the {} .
  cb = document.getElementsByName(item)[0];
  • We've called our checkbox 'cb'.
  • This time we're finding our element by name instead of tag so we use .getElementsByName. Then we choose the first in the list ([0]).
  • Now we can add our condition.
  if (cb.checked) {
  } else {
  }
  • If our checkbox 'cb' is checked, then we'll run some code to make the text grey, otherwise we'll run code to make it black.
  • The text isn't part of our checkbox, so we need to find the element it belongs to, which in this case is the parent element (our <input> element is directly inside our <li> element) so we use .parentElement.
  • The full code is then as follows.
function toggleCheckbox (item) {
    cb = document.getElementsByName(item)[0];
    if (cb.checked) {
        cb.parentElement.style.color = "gray";
    } else {
        cb.parentElement.style.color = "black";
    }
}
  • Run that and try it out for yourself.

Final Code

en/web_development/lists/javascript.txt · Last modified: 2023/08/16 09:33 (external edit)