Hackernoon logoJavaScript DOM and how to navigate it with a <form> example, Part 2: Collecting form values by@marcellamaki

JavaScript DOM and how to navigate it with a <form> example, Part 2: Collecting form values

Author profile picture

@marcellamakiMarcella Maki

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.

Collecting form data

First, pay attention to scope

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.

Relatedly, pay attention to when you are calling values

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.

  1. I can’t use getElementByID(). Some sort of query selector is probably the best option
  2. I want the value of the field to be updated based on some certain event
  3. I want to make sure I don’t get back an undefined value or error
//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

  1. Before I did anything, I console logged “I’m connected”, and checked this to make sure that my JavaScript file and my index.html are communicating. I console log every step of the way because there is nothing like assuming that since something is simple everything is working smoothly, and then 2 hours later you have a dumb bug you can’t track down and it’s really just because a variable you declared 200 lines of code ago was not defined how you expected
  2. I used an on change for the input value. There are other event listeners that could work here, maybe something tied to a form submit, but I find this one simple to test in the console. It updates the value as the user is typing. I also like to have each of my functions manage a minimal amount of processes. Rather that having one giant function that gathers values for every form field and then submits, I’d rather break things down into one function for each field, with a suitable event listener and CSS selectors, and then have one function for managing submission.
  3. I declared the form variable outside of the event listener, so that I can use it throughout my file. However, I define the variable within the event listener, meaning it only becomes defined once there is a value in the input field.

Make sure you’re using the right event listener

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)
})

Make sure you’re getting a value that’s helpful

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

Creating an object with form data

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.

Why use an object

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.

Resources

Tags

Join Hacker Noon

Create your free account to unlock your custom reading experience.