Skip to content

Prep 5: Forms and Events

Textbook Reading

Form & Function

Your goal is to build a basic form (based on the knowledge from the readings) that will let a user dynamically modify parts of the page. You don’t need to write any CSS for this activity.

The user should be able to specify a number of random images to generate, then click generate to add them to the page:

Selecting a number of images and clicking generate adds images to the page

They can also select a background color and click change to update the page background:

Selecting a background color and clicking change updates the page background

Getting Started

First, download the starter code here:

Unzip it to cs343/preps/05 or somewhere else safe and accessible. Open the index.html and script.js files in VS Code.

The starter code is intentionally barebones. You’ll need to write virtually all of the HTML and JavaScript yourself.

Forms in JavaScript

I recommend referencing the blog post on handling forms.

The important takeaways are to:

  • Use event.preventDefault() in your event handlers to prevent the default form submission behavior.
    • Otherwise, the page will refresh!
  • Access form elements and data using FormData, or by directly referencing the input elements via their ids.
    • If you have a FormData object, you can use its .get() method
    • If you have a reference to the input element, you can use .value to get the current value of an input element.

As a quick reference, here’s a basic outline of how to handle form submissions in JavaScript:

// Get the form
const form = document.getElementById("my-form");

// Add an event listener for the form submission
form.addEventListener("submit", onFormSubmit);

// Function to handle the form submission
function onFormSubmit(event) {
    event.preventDefault(); // IMPORTANT!

    // Your code to handle the form submission goes here
}

Anonymous Functions, Anyone?

You can also create a function directly within the addEventListener call, like this:

form.addEventListener("submit", function(event) {
    event.preventDefault(); // IMPORTANT!

    // Your code to handle the form submission goes here
});

This is actually preferred, since it puts the event handling logic right where the event listener is added, making the code easier to read and avoids polluting the global namespace.

Part 1: Forms

In the body, create the following elements:

  1. Create a form for specifying the number of images:

    • Give this form the id of "image-form".
    • It should have a label that says “Number of images:”,
    • An input that only lets you enter numbers (type="number"),
    • And a button of type "submit" that says “Generate”.

      Hint: Button Syntax

      Note that buttons use the <button> tag, and they have both a start and an end tag, with the button text placed between them:

      <button type="submit">Generate</button>
      

  2. Create a second form for specifying the background color:

    • Give this form the id of "background-form".
    • It should have a label that says “Background color:”,
    • An input that lets you pick a color,
    • And a button of type "submit" that says “Change background”.
  3. Afterwards, create an empty div to store your images.
    • Give this the id of "images".
  4. I recommend that you give any input you wish to access via JavaScript a unique id!
    • Like the input fields, the buttons, the div, etc.
    • Alternatively, you can use FormData, which can help access the entire form’s data.

Part 2: Functionality

In script.js, add JavaScript code so that:

  1. When the “Generate” form is submitted (the "submit" event):
    • It should clear all images already in the div. (remember how to do this?)
    • It should add random images to the div based on the number specified in the form:
      • Images should be 200x200 in size
      • Images should be from Lorem Picsum: https://picsum.photos/[WIDTH]/[HEIGHT]?random=[NUMBER] (replace [WIDTH], [HEIGHT], and [NUMBER])
      • Each image should be different (hint: change [NUMBER] each time you add an image - use an index or a counter)
    • Tip: Recall how to create and append elements to the DOM (make a helper method!):
      1. Use document.createElement to create a new "img" element.
      2. Set the src attribute of the image to the appropriate URL.
      3. Append the image to the div containing the images.
  2. When the “Change background” form is submitted:
    • It sets the background color of body to the color specified in the form
      • You may set an inline style to accomplish this (using the style property of an element)
      • Just set document.body.style.backgroundColor to the selected color.
Hints
  • Remember to prevent the default form submission behavior using event.preventDefault().
  • Values may need to be converted from strings to numbers using parseInt(...) when necessary.
  • You can clear all contents by setting element.textContent = "" or calling element.replaceChildren().

Submit both index.html and script.js to Gradescope.