

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 Object
Person.name = nameField
Person.age = ageField
Person.profession = professionField
addPersonToEvent(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.
Create your free account to unlock your custom reading experience.