span Bodingles | Colt Steele

The Web Developer Bootcamp 2024

Colt Steele

Back to JavaScript Index Page


JavaScript Form Events
Form Events

In order to understand how JavaScript can process forms, we need to rewind a little and remind ourselves how a basic HTML form is processed.

The basics of an HTML form is the form element which is used to define a form. Once the form is defined you then have some form inputs for user to input data into the form. Once the data is entered, the form is by default, processed by the action attribute of the form. This action attribute tells the form where to go, usually a separate web page, to process the form data.

For example:

  • <form action="/formProcess" id="tweetForm">
    • <input type="text" id="userName" placeholder="User Name">
    • <input type="text" id="tweet" placeholder="Tweet">
    • <button>Submit</button>
  • </form>
Let's dissect this form:
  • form action="/formProcess" directs the form to open a webpage called formProcess to process the form data.
    • (if we actually ran this form you would get the dreaded 404 error, page not found, because the web page formProcess doesn't actually exist).
    • it also assign an id of tweetForm which we will use for the JavaScript processing
  • next we have two basic inputs, one for a userName input and the other one for a tweet input.
  • and finally, a submit button to submit this form.

And here is the form as defined:

*note: this form is a template for discussion purposes only. It does NOT work but there is a fully functional "working" form at the end of the page, here.

One more page addition needs to go after the form itself. We need to create a space for our new tweets to reside. So, after the form element, we will create an empty unordered list with an id that we can reference within our JavaScript. We'll use an id of tweets. The code is simply:

  • <ul id="tweets"></ul>
This will give us an empty container where we can add line items <li> for each new tweet.




Processing the Form

Now that we have a form to work with, let's talk about the action attribute. By default, the form element will got to wherever the action attribute sends it for processing. Now in some instances this may be desirable. If you have a form to create a new login, once you verify the data you might redirect this to a separate web page to process that data and upload it to a database.

But what if you don't want any kind of redirection. What if you want to stay on a page and just update some comments, or tweets? This is where JavaScript processing comes in very handy.

There are a few steps involved for the processing of the form with JavaScript.

1). We need to provide a way for JavaScript to utilize the form elements. We do this by creating a variable to reference the form. In this example, we are referencing the form by ID. While this is not necessary on this page (because we only have one form on the page), we show the process here to demonstrate how to handle multiple forms on a page.

  • const tweetForm = document.querySelector('#tweetForm');
    • // assigns the variable tweetForm to the form element with the id of tweetForm, which is the HTML Form element, itself
While we are assigning variables, we can also assign the variable we need for our empty ul we created to contain our tweets, and also the variables for our userName and tweet inputs.
  • const tweetsContainer = document.querySelector('#tweets');
  • const userName = document.querySelector('#userName');
  • const tweet = document.querySelector('#tweet');

2). Next we need to assign an event listener to the form via a form submit event, to detect when the form is submitted.

  • tweetForm.addEventListener('submit', function (evt) {
    • // assigns the form event (submit) to tweetForm to listen for when the form is submitted.
    • // notice also the we are using the event object variable evt
  • })

3). The next thing we want to do is to utilize an object event property called preventDefault(). This property prevents the default form action of either reloading this page, or redirecting to a new page, from happening. This is a property of the object event evt, so the code is:

  • evt.preventDefault();

4). Next we need to actually process the form inputs userName and tweet and add them to new list items (li) that we will have to create. There are several steps for this, so we will create a separate function for this below, but we will go ahead and call this function now:

  • addTweet(userName.value, tweet.value)
This will call the addTweet function passing in the value of the variables that represent the userName and tweet values that the user entered into our form.

5). and finally, we need to clear out the form fields of any data, so we can add a new entry, if desired.

  • userName.value = '';   // empty string
  • tweet.value = '';   // empty string

And now, let's write the function to take our form data and create our new <li>'s. Remember, we called this function addTweet in step 4 above.

1). First, we'll create the processing function. We'll start by defining the function itself:

  • const addTweet = (userName, tweet) => {
    • // creates the addTweet function that receives two variables, userName andtweet

2). Create the two new HTML elements that we need:

  • const newTweet = document.createElement('li');
  • const boldElement = document.createElement('b');

3). Next we want the user name text to be bold so we'll append boldElement with the username that was passed into this function

  • boldElement.append(username);
    • // puts the username inside a BOLD element
  • newTweet.append(boldElement);
    • // puts the bolded username inside newTweet

So newTweet now contains the bold username.

4). Now we want to add - (a dash) and the newTweet.

  • newTweet.append(`- ${tweet}`)
    • // we're adding "-", plus the new tweet that was passed into the function to the end of newTweet

5). and Finally, we add the newly built tweet, which contains username - newTweet to the parent ul container that we defined above as tweetsContainer. This container was derived from the id that was created when made the parent ul in the HTML markup.

  • tweetsContainer.append(newTweet);

This should now update our webpage with the new tweet, right below our HTML form.




Final Code

Here is the final code.

  • HTML Markup
  • // create the form element
  • <form action="/formProcess" id="tweetForm">
    • <input type="text" id="userName" placeholder="User Name">
    • <input type="text" id="tweet" placeholder="Tweet">
    • <button>Submit</button>
  • </form>
  •  
  • // create the empty ul element which will be the tweet container
  • <ul id="tweets"></ul>
  •  
  • JavaScript
  • // define the variables
  • const tweetForm = document.querySelector('#tweetForm');
  • const tweetsContainer = document.querySelector('#tweets');
  • const userName = document.querySelector('#userName');
  • const tweet = document.querySelector('#tweet');
  •  
  • // add the event listener assigned to a submit event
  • tweetForm.addEventListener('submit', function (evt) {
    •  
    • // override page reload or redirect
    • evt.preventDefault();
    •  
    • // call the function addTweet and pass in the user input values for userName and tweet
    • // wrap this in a for loop that does not allow for blank entries
    • if (userName.value != "" && tweet.value != "") {
      • addTweet(userName.value, tweet.value)
    • }
    • This error check works very well. If either input field is left blank, it does NOT add a new tweet entry, and it resets the form fields.
    •  
    • // clear the HTML form fields for new input
    • userName.value = '';   // empty string
    • tweet.value = '';   // empty string
  • });
  •  
  • JavaScript
  • // create the new HTML elements and append with the user input data
  • const addTweet = (userName, tweet) => {
    •  
    • // create the new <li> element as a new tweet container
    • const newTweet = document.createElement('li');
    •  
    • // create a <i> element to italicize the username
    • const italElement = document.createElement('i');
    • // place the userName inside the italElement
    • italElement.append(userName)
    •  
    • // create a <b> element to make the italicized username, bold
    • const boldElement = document.createElement('b');
    • // place the italicized userName inside the boldElement
    • boldElement.append(italElement)
    •  
    • // place the now bold & italic userName inside the newTweet <li>
    • newTweet.append(boldElement);
    •  
    • // add the New Tweet data to the end of newTweet
    • newTweet.append(` - ${tweet}`)
    •  
    • // add the newTweet to the tweetsContainer
    • tweetsContainer.append(newTweet);
  • }



Final Product

And here is the final product:

    Back to Top