User Tools

Site Tools


en:web_development:lists:javascript

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
en:web_development:lists:javascript [2021/12/02 13:42]
mag
en:web_development:lists:javascript [2023/08/16 09:33] (current)
Line 1: Line 1:
-====== Web Development Lesson - Lists ======+====== Web Development Lesson - Lists ======
 ===== Javascript 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 ==== ==== Setup ====
-  * We'll use the first file you created in this lesson called 'lists.html', so open that file in Visual Studio Code.+  * We'll use the first file you created in this lesson called '[[https://techschool.murraygunn.id.au/webdev/classes/lists/3/lists.html|lists.html]]', so open that file in Visual Studio Code.
   * Create a file called 'lists.js' in the same directory.   * Create a file called 'lists.js' in the same directory.
   * We'll also return to [[https://jsfiddle.net|jsfiddle]] to try out a few things.   * We'll also return to [[https://jsfiddle.net|jsfiddle]] to try out a few things.
Line 38: Line 40:
 <code>document.body.innerHTML = cars[0];</code> <code>document.body.innerHTML = cars[0];</code>
   * Run the code and see that it displays 'ferrari', the first item.   * Run the code and see that it displays 'ferrari', the first item.
-  * Try changing th enumber inside the <html> [] </html> and check the results to be sure you understand how it works.+  * Try changing the number inside the <html> [] </html> 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.   * 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 <html></body></html> tag.   * Open 'lists.html' and add an unordered list just before the closing <html></body></html> tag.
-<code><h2>Players</h2>+<code>  <h2>Players</h2>
   <ol></ol>   <ol></ol>
 </body></code> </body></code>
Line 101: Line 103:
 ==== Iterating Arrays ==== ==== Iterating Arrays ====
   * So now that you understand how for loops work, we can apply it to an array.   * 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.   * Let's edit the for loop you have already.
 <code>var text = ""; <code>var text = "";
 for (i = 0; i < 10; i++) { for (i = 0; i < 10; i++) {
- text += i + "<br />";+ text += cars[i+ "<br />";
 } }
 document.body.innerHTML = text;</code> document.body.innerHTML = text;</code>
Line 110: Line 113:
 <code>var carList = ""; <code>var carList = "";
 for (i = 0; i < 10; i++) { for (i = 0; i < 10; i++) {
- carList += i + "<br />";+ carList += cars[i+ "<br />";
 } }
 document.body.innerHTML = carList;</code> document.body.innerHTML = carList;</code>
Line 116: Line 119:
 <code>var carList = ""; <code>var carList = "";
 for (i = 0; i < 3; i++) { for (i = 0; i < 3; i++) {
-  carList += i + "<br />";+  carList += cars[i+ "<br />";
 } }
 document.body.innerHTML = carList;</code> document.body.innerHTML = carList;</code>
-  * If you runt his now, it should show all 3 cars, one on each line.+  * 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.   * Now have a go at applying this yourself to the list of players in Visual Studio Code.
   * Here's my version.   * Here's my version.
Line 128: Line 131:
  
 window.onload = function () { window.onload = function () {
 +  playerList = "";
   for (i = 0; i < 4; i++) {   for (i = 0; i < 4; i++) {
     playerList += "<li>" + players[i] + "</li>";     playerList += "<li>" + players[i] + "</li>";
Line 139: Line 143:
   * Let's see how this works in jsfiddle.   * Let's see how this works in jsfiddle.
   * Add an alert to your Javascript code.   * Add an alert to your Javascript code.
-<code>alert("cars has " + cars.length + "items.");</code>+<code>alert("cars has " + cars.length + " items.");</code>
   * Run that and check that it does what you think it should.   * 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.   * So we can change our continuing condition for the list of players as follows.
Line 145: Line 149:
   * Run it now and see that it shows exactly as many players as you have in your list.   * 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.   * 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.
 +<code>var x = 2;
 +if (x == 2) {
 + alert 'the condition is true';
 +}</code>
 +  * The basic structure of this code is <html>if (condition) { code to execute if true }</html>.
 +  * We have a condition inside the <html> () </html>, and only if that condition is true do we run the code inside <html> {} </html>.
 +  * In this case, our condition is <html> x == 2 </html>, which checks the value of <html> x </html> and the value of <html> 2 </html>. If the value of <html> x </html> is 2, then it will run the code displaying an alert.
 +  * Since we've just defined <html> x = 2 </html> (first line), this condition is true and the alert will be displayed. Try it now.
 +  * Now change the value of <html> x </html> to 5 (or anything but 2) and run the code again.
 +  * Nothing is displayed. Let's add a message if it fails too.
 +<code>var x = 2;
 +if (x == 2) {
 + alert 'the condition is true';
 +} else {
 + alert 'the condition is false';
 +}</code>
 +  * Here, we have added <html>else</html> with code that will run if the condition is not met. Run the code again with the wrong value of <html> x </html> 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.
 +<code>        <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></code>
 +  * <html>onchange=""</html> 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 <html>""</html>.
 +  * 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.
 +<code>function toggleCheckbox(item) {
 +}</code>
 +  * First we define the code as a 'function' using <html>function</html> 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 <html>onChange</html> attribute (the name of the checkbox) to the variable called <html>item</html>.
 +  * Finally, we have <html> {} </html> 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 <html> {} </html>.
 +<code>  cb = document.getElementsByName(item)[0];</code>
 +  * We've called our checkbox 'cb'.
 +  * This time we're finding our element by name instead of tag so we use <html>.getElementsByName</html>. Then we choose the first in the list (<html>[0]</html>).
 +  * Now we can add our condition.
 +<code>  if (cb.checked) {
 +  } else {
 +  }</code>
 +  * 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 <html><input></html> element is directly inside our <html><li></html> element) so we use <html>.parentElement</html>.
 +  * The full code is then as follows.
 +<code>function toggleCheckbox (item) {
 +    cb = document.getElementsByName(item)[0];
 +    if (cb.checked) {
 +        cb.parentElement.style.color = "gray";
 +    } else {
 +        cb.parentElement.style.color = "black";
 +    }
 +}</code>
 +  * Run that and try it out for yourself.
 +
 +==== Final Code ====
 +  * [[https://jsfiddle.net/maganthro/t3bq247f/13/|jsfiddle]]
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/es.php|lists.html]]
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/listsjs.php|lists.js]]
 +  * [[https://techschool.murraygunn.id.au/webdev/classes/lists/4/lists.html|final result]]
  
 [[en:web_development:lists:exercise|Next: Exercises]] [[en:web_development:lists:exercise|Next: Exercises]]
en/web_development/lists/javascript.1638481326.txt.gz · Last modified: 2023/08/16 09:33 (external edit)