OIM3690 - Web Technologies

contain

JavaScript - Arrays

Arrays in JavaScript

  • An array is a special variable that can store multiple values in a single place.
    • Each value is stored at a specific index, starting from 0.
    • Arrays have built-in methods to add, remove, and loop through items.
  • Create and Access an Array
    const fruits = ['Apple', 'Banana', 'Orange'];
    console.log(fruits.length); // 3 
    
    const first = fruits[0];
    console.log(first); // Apple  
    
    const last = fruits[fruits.length - 1];
    console.log(last); // Orange  
    
    console.log(first[1]); // What is the output?
    

Working with Radio Button Arrays

  • Example:
    <form action="" method="post" id="my-form">
      <label><input type="radio" name="colors" value="red" />Red</label>
      <label><input type="radio" name="colors" value="blue" />Blue</label>
      <label><input type="radio" name="colors" value="yellow" />Yellow</label>
      <label><input type="radio" name="colors" value="green" />Green</label>
    </form>
    
  • JavaScript treats same-name radio buttons as a collection (RadioNodeList) accessible through the form.elements API — similar to an array.
    const colors = document.getElementById("my-form").elements["colors"];
    console.log(colors[0].checked);
    console.log(colors[0].value);
    
  • How do we get value of the checked radio button?

Use if Statements?

  • Possible solution:
    let userChoice;
    if (colors[0].checked) {
      userChoice = colors[0].value;
    } else if (colors[1].checked) {
      userChoice = colors[1].value;
    } else if (colors[2].checked) {
      userChoice = colors[2].value;
    } else {
      userChoice = colors[3].value;
    }
    console.log(userChoice);
    
  • It does not look like a very good solution. Why?
    • What if we add or remove a radio button from the form?

for Statement

  • Syntax (via MDN)
    for ([initialExpression]; [condition]; [incrementExpression]){
      statement
    }
    
  • Example:
    let userChoice;
    for (let i = 0; i < colors.length; i++) {
      if (colors[i].checked) {
        userChoice = colors[i].value;
        // break; // exit the loop
      }
    }
    console.log(userChoice);
    

Exercise: ex18.html

  • Download ex18.html from GitHub (OIM3690/resources/templates)
  • Clicking button should:
    • Change background color.
    • Display selection(s) in textarea.
  • Extra: add a dropdown menu (select and option) and use JavaScript to get the selected value
  • Update sitemap.html and commit/push to GitHub.

Questions?