β Learn Javascript
Use form data via the Document Object Model (DOM)
slides | md
Review the following sections and perform the activities on your own or with your group. Perform the task(s) when you see this π emoji
Students who complete this module will be able to:
document
π View these properties and functions in the console (or access them with javascript using dot syntax).
window
{}
f
alert(123)
window.alert(123)
window.document
// get web page url property window.document.URL // set a new location for this window document.location = "https://davidson.edu" // get property window.document.body.style.background // set (same) property document.body.style.background = "red"
Some properties can be accessed directly using "direct selection"
// replace the content of the body document.body.innerHTML = "π" // get a form value document.myForm.myInput.value
<p id="greeting">Hello world</p>
// use #id to store reference to element let ele = document.querySelector("#greeting"); // get the text console.log(ele.textContent); // or set the text ele.textContent = "Hello world!";
<p>Red</p> <p>Green</p> <p>Blue</p>
// return an array of all <a> elements on the page: let ele = document.querySelectorAll("#greeting"); // -> then use a loop to address them
<form>
<input>
preventDefault
<form action="#" class="myForm"> <input type="text" id="color"> <button id="submit">Submit</button> </form>
// get reference let ele = document.querySelector(".myForm"); // listens for when the form was submitted (any button inside) ele.addEventListener("submit", function(e) { e.preventDefault(); console.log(colorVal); })
submit
input
<form action="#"> <input type="text" id="color"> <input type="submit"> </form>
document.addEventListener("submit", function(e) { e.preventDefault(); let colorVal = document.getElementById("color").value; console.log(colorVal); document.body.bgColor = colorVal; })
π Try it out
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');
Overview: Events and using forms with Javascript and jQuery
// 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)