In Part 1, I did a quick review of the DOM and some CSS selectors that are helpful with collecting values from an HTML form.
In this portion, I’m looking at different ways to capture those values when you don’t have an index.html that is particularly straightforward to work with, such as when you can’t just use getElementByID(). This will include things to think about like scope, event listeners, more on CSS selectors, and some tricks I use to check my code as I’m writing.
Scope in JavaScript determines the accessibility of different variables that have been assigned. Variables can have either a local or global scope. Global variables are accessible anywhere throughout your filed, whereas local variables are accessible only within a function.
For example:
// Global variables are declared outside of a function and accessible within it
var name = "Marcella"
function sayHi(name) {console.log(`Hi ${name}`)}// console logs "Hi Marcella"
// Local variables are declared within a function and outside the // function are undefined
function sayBye() {var myName = "Marcella"}
console.log(myName)//reference Error
You can see this tested out in the console in Chrome Dev Tools, which is a great place to try out some JavaScript you’re writing.
Let’s say I have an HTML form with a name field, the code looking something like this
index.html
...<form><div><label>Name<input type="text" name="name"></label></div></form>...
And I’m writing a bit of JavaScript to capture the value of that input field. Here are some things I know going in.
//index.js
window.onload = function(event) {//console.log("I'm connected!")
let form = document.forms[0];let nameField;
document.addEventListener("change", function(event){
nameField= form.querySelector('input\[name="name"\]').value;
console.log(nameField);
})
}
My strategy
This may seem obvious, but double check the event listener you’re using. If you write with additional JavaScript frameworks or libraries that have different conventions or ways to call an event listener, just take a minute to look it up.
If you’re using .onchange, you want to write
object.onchange = function(){myScript};
If you’re using addEventListener
object.addEventListener("change", myScript);
An example in action
document.addEventListener("change", function(event) {myOption=form.querySelector('select[name="myOptions"]').value;console.log(myOption)})
If you have a form field that is a checkbox or a radio button, using .value is probably not your best option. With a checkbox, if you use .value with an on change event, the return value is “on” whether the checkbox is selected or deselected. A boolean value would be much more useful, and using .checked returns a boolean.
document.addEventListener("change", function(event) {selected=form.querySelector('input[name="selected"]').checked;console.log(selected)})
//console logs either true or false
Once you have form data, there are two possible steps, either rendering it to the page as a preview or submitting it to the backend.
Adding data from a form and rendering it to the page before the user decides to submit is a great way to preview information. Essentially, all you need to do is write a function that gathers the information from the form and creates new elements and renders the text to the page on an “add” event (probably a button onclick). Using an object also makes things simpler for sending information to a database. You can create the object once and use it for multiple purposes.
Here is an example of a very straightforward object creation, and rendering a string of that object’s data to the document body.
let addButton = form.querySelector("button.add")// console.log(addButton) - to check it's the right element
addButton.addEventListener("click", createNewPerson)
function createNewPerson(event) {event.preventDefault()Person = new ObjectPerson.name = nameFieldPerson.age = ageFieldPerson.profession = professionFieldaddPersonToEvent(Person)}
function addPersonToEvent(person) {
let newPerson = "Name: " + person.name + ", Age: " + person.age + ", Profession: " + person.profession
let thisAttendee = document.createTextNode(newPerson)
let linebreak = document.createElement("br")
document.body.appendChild(thisAttendee)
}
Here, I’ve done a few things. I’ve selected the add button on my form and added an event listener to it — remembering to use the right syntax — , grabbed the information from my form, created a new object with it, and then rendered the information to the DOM using .appendChild().
In Part 3, I’ll write about full CRUD functionality for data on the page, rendering information strategically (rather than just document.body, which tacks it onto the end) and preparing JSON to be sent to the backend.
Object.create()_The Object.create() method creates a new object with the specified prototype object and properties._developer.mozilla.org
Demystifying JavaScript Variable Scope and Hoisting_This article looks at two fundamentals of JavaScript programming - variable scope and hoisting._www.sitepoint.com
CSS Selectors Reference_Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript…_www.w3schools.com
EventTarget.addEventListener()_The EventTarget.addEventListener() method adds the specified EventListener -compatible object to the list of event…_developer.mozilla.org