25 Jul 2018

Code Companion #10: Forms

Introduction

In this tutorial we’ll be building off of the previous tutorial updating our user prompt to a more familiar web UI—forms.

From here on we’ll be continually adding features to this application building a full blown Pokedex.

Setup

First we’ll make a new folder for our project.

mkdir forms
cd forms

Within this directory we’ll create two new files, an HTML file and a JavaScript file similar to what we did previously in Code Companion #9.

touch main.js index.html

Form

The first thing we’ll do is add our HTML, including a form, to index.html.

<!DOCTYPE html>
<html>
  <head>
    <title>Code Companion - Forms</title>
    <meta charset="utf-8">
    <script src="main.js"></script>
  </head>

  <body>
    <form id="pokedex">
      <p>Pokemon name:</p>
      <input type="text" name="pokemon">

      <p>Description:</p>
      <textarea name="description" rows="10" cols="30"></textarea>

      <br>
      <button type="submit">Add to Pokedex</button>
    </form>

    <h2>Pokemon:</h2>

    <ul id="pokemon-list"></ul>
  </body>
</html>

First we begin with a form tag setting its id attribute to pokedex. This id is what we’ll be using to access the values a user enters into the form.

Within the form we’ve added two inputs: one using the input tag and another using the textarea tag. The noteworthy parts here are the name attributes. The values set to name are what we’ll use to access the specific values within the form. Finally, we have a button that will be used to submit the form.

Below our form we also have an unordered list which should look familiar if you worked through Code Companion #9.

Event Listener

Now that we have our form setup we can setup an event listener for the form.

function addToPokedex(event) {
  event.preventDefault();
  console.log('event ', event);
}

document.addEventListener('DOMContentLoaded', function() {
  let form = document.getElementById('pokedex');
  form.addEventListener('submit', function() {
    addToPokedex(event);
  });
});

First we add an event listener for DOMContentLoaded. Within this event we add another event listener for our form. Unlike our previous example where we were listening to a click event, we’re now waiting for the submit event.

Once this event has fired we call the addToPokedex function passing it event which is an object representing the event of the event listener. This object contains multiple properties including a property that allows us to access the values in the form which we’ll get to shortly.

Within our addToPokedex function we first call event.preventDefault() which prevents the default form event from firing. In this case, we’re preventing our form from initiating a request to a backend since we don’t have one. For now, we’re doing everything client-side.

Open index.html in Chrome, add some values to the form, click submit, and you should see the event object logged to the console.

Logging the event object

Accessing form values

Now that our function has access to the event object, we can access the values within our form.

function addToPokedex(event) {
  event.preventDefault();
  let name = event.target.pokemon.value;
  let description = event.target.description.value;
  console.log(`Name is ${name}`);
  console.log(`Description is ${description}`);
}

To access our form object we use event.target. Following target are the name attributes we specified within our form (pokemon and description) with .value after each name to get the value of each input. We then log the values for name and description to verify we’re getting the values we expect.

Refresh your page, complete the form again, and you should see your values printed to the console.

Logging the event object

Now that we have the values within our form, we can create a new list element and add it to the unordered list.

function addToPokedex(event) {
  event.preventDefault();
  let name = event.target.pokemon.value;
  let description = event.target.description.value;

  let listItem = document.createElement('li');
  let list = document.getElementById('pokemon-list');

  listItem.innerHTML = `${name} - ${description}`;
  list.appendChild(listItem);
}

Go back to Chrome, complete the form, and you should see the list update with your Pokemon.

Add Pokemon to list

Resetting the Form

Our list is now updating correctly but our form maintains its original state with the user’s values within the form’s inputs. Let’s add an update to clear this form once the form has been submitted.

function clearForm() {
  document.getElementById('pokedex').reset();
}

document.addEventListener('DOMContentLoaded', function() {
  let form = document.getElementById('pokedex');
  form.addEventListener('submit', function() {
    addToPokedex(event);
    clearForm();
  });
});

Here we’ve added a clearForm function that uses getElementById to access the form. We then call .reset() to reset the form and call clearForm() within the event listener for submit.

Now when you submit the form the list should populate with your values and reset the form for the user.

Resetting the form

Conclusion

Before we finish, add your latest changes to Git.

git init
git add .

Then add a commit message.

git commit -m "Add forms"

Then push these changes up to GitHub.

git push origin master

Exercise

For some extra practice, see if you can update main.js to avoid adding empty list elements to the DOM if the user submits an empty form.


Before you go...

Feeling stuck copying and pasting from tutorials that don't build realistic applications?

Become an Angular developer by building a real application using open-source libraries with a real API and database.

"The advice and techniques in this book landed me my dream job and literally doubled my salary. Well worth the $99 bucks, so much so that I have been waiting for it to be for sale just to pay the man for the good he has done to my career." -Levi Robertson

CLICK HERE FOR A FREE 8 CHAPTER PREVIEW OF THE ANGULAR TUTORIAL

Learning a front-end framework is hard. "Getting started" tutorials cover the basics but you leave thinking, "Okay, now how do I build something with this?"

The truth is, getting started tutorials aren't all that great for beginners. They're demos to highlight as many features as quickly as possible.

They're great for showing off what a framework can do. They aren't so great for teaching you how to build web apps.

The end result is a basic application that doesn't mimick what it's like building real applications as a front-end developer.

You'll work with a mocked API and database. Application architecture isn't covered. Automated testing is skipped altogether.

Trust me, I've been there. But those days are over.

With The Angular Tutorial, you'll learn how to build applications using a real API and database. You'll leverage 3rd party APIs like Zomato, Google Places, and open-source libraries just as you would in a real job.

The Angular Tutorial assumes you have no previous knowledge of the Angular framework. It starts at the very beginning.

Every piece of code is explained and tested to make you interview ready.

Ready to get started? 👇