← Learn Javascript

The DOM & Web Forms

Use form data via the Document Object Model (DOM)

slides | md

Introduction

Notes

Review the following sections and perform the activities on your own or with your group. Perform the task(s) when you see this πŸ‘‰ emoji

Learning Objectives

Students who complete this module will be able to:

  • Demonstrate how to
  • Explain
  • Use Javascript to
  • List
Homework

About the DOM

  • A browser parses a page and creates a document object with all the page elements
  • This makes it easy to select element and access their HTML and CSS code.

The window object

  1. Type window and press return
  2. Expand a property {} or function f to see more.
  3. Functions can be called in the console: alert(123) or window.alert(123) and press return.
πŸ‘‰ View these properties and functions in the console (or access them with javascript using dot syntax).

window.document

  • window includes the page and browser tab
  • window.document or just document contains structure, content, and properties for the page only.
// get property
window.document.body.style.background
// set the property
document.body.style.background = "red"

// get web page url property
window.document.URL
// set a property
document.location = "https://davidson.edu"

// replace the content of the body
document.body.innerHTML = "πŸ˜ƒ"
πŸ‘‰ Explore these in the console

Select elements with document.querySelector()

  • The number of properties that can be accessed using direct selection (what we've done so far) is limited.
  • document.querySelector() returns references to any element you like using its CSS selector.
<p id="greeting">Hello world</p>
// store reference to element
let ele = document.querySelector("#greeting");

// get the text
console.log(ele.textContent);

// or set the text
ele.textContent = "Hello world!";

Selecting Many HTML elements

Example:

Red

Green

Blue

<p style="color:red">Red</p>
<p style="color:green">Green</p>
<p style="color:blue">Blue</p>
// get array of all <p> elements on a page 
let eles = document.querySelectorAll("p");
// use a loop to log them
eles.forEach(function(ele){
	console.log(ele)
})

Listening for Form Events

πŸ‘‰ In codepen create <form> and <input> elements and add a submit listener.

<form action="#" class="myForm">
	<input type="text" id="color">
	<button type="submit">Submit</button>
</form>
// get reference
let myForm = document.querySelector(".myForm");
// listens for when the form was submitted
myForm.addEventListener("submit", function(event) {
	console.log("Form was submitted!");
})
❌ This is going to have issues. Anyone know why?

Getting Form Data

  • By default all web forms load a new page. Use preventDefault on the returned event object to prevent this.
  • Set the background color by referencing the this (the form) .color (the input's id) and .value (its value).
// get reference
let myForm = document.querySelector(".myForm");
// listens for when the form was submitted
myForm.addEventListener("submit", function(event) {
	event.preventDefault();
	document.body.bgColor = this.color.value;
})

Change your HTML to start building the SUS form

Follow the book's prompt to make the form for Usability Test...

<form action="#" class="myForm">
	<input type="number" id="q1">
	<input type="number" id="q2">
	<button type="submit">Submit</button>
	<input type="number" id="answer">
</form>
myForm.addEventListener("submit", (event) => {
	event.preventDefault();
	let q1 = Number(this.q1.value);
	let q2 = Number(this.q2.value);
	// add all converted responses
	let answer = (q1 + q2);
	// store in a new input and log to the console
	this.answer.value = answer;
	console.log(answer);
});

Next steps

  1. Try the Exercises below.
  2. Start working on homework listed in the schedule.
  3. Continue to the next lesson.

Exercises

πŸ‘‰ Try it out

  1. The Lottery v.2 - responding to events, The Lottery v.3 - displaying content in the browser
    • Already finished? Add a way to spend more money in the lottery game
  2. Exercises from Eloquent Javascript

References

jQuery and The DOM

jQuery is a Javascript library you will see often in code references. It provides easy access to properties and methods in the HTML DOM, but it is better to learn "pure JS" (a.k.a. "vanilla").

NOTE: youmightnotneedjquery.com

// select all divs, set backgrounds red
$('div').css({ 'background': 'red' });
// select all elements with myClass, add text to end
$('.myClass').append(' - here is some new text');

Forms and Events with jQuery

Overview: Events and using forms with Javascript and jQuery

NOTE: youmightnotneedjquery.com

// click event with callback
$('#submitButton').click(function() {
	// set the value of a form element
	$('#color').val("purple");
	// do not perform the default form action
	return false;
});

Presentation comments ...

--- ## Contents 1. [Introduction](#introduction) 1. [Selecting HTML elements](#selecting-html-elements) `5 min` 1. [Next steps](#next-steps) 1. [Exercises](#exercises) 1. [References](#references)