Getting Started with jQuery (Part 3): Add and Remove HTML Elements on a Page

In this third part, of our five parts jQuery tutorial, we will continue to explore how we can use  jQuery DOM manipulation helpers to add and remove HTML elements from our page without refreshing the page. You see this being used very often in modern web pages, where text and graphics are constantly added or removed from the page once you have entered more data.

We will build upon our knowledge of jQuery DOM manipulation in the previous two parts: Getting Started with jQuery (Part 1): How to Manipulate the DOM and Getting Started with jQuery (Part 2): More DOM Manipulation and Forms Handling.

What Will We Be Building?

In this tutorial, we will be building a simple To-Do list application. We will learn how to use the jQuery library to add and remove HTML elements from our web page. Using this knowledge, we will then continue to build our To-Do list application with the functionality below:

  • Have a form to allow us to add new items

  • Allow us to remove existing items that we have added

  • Allow us to select an existing item to show more details

  • Allow us to filter items by categories

Building Our Skeleton HTML for Our To-Do List

We will first mock-up our To-Do list in HTML. In our mock-up HTML, we will put a static list of items for now as well as a form for us to add new items later. Our HTML mock will look like this:

Our CSS styling will look like this.

Our To-Do list will look like the following after we have applied the HTML and CSS styles:

Pro-Tip: Always Do an HTML Mock-up First

By doing a mock-up, we can then focus on making our To-Do list look the way we want it to before adding any interactive functionality to it. This will enable us to follow a step by step methodology when creating our web application where we will not be juggling between making our app look presentable and also trying to debug our jQuery code.

A Short Explanation of the HTML Mock-up

Let’s take a closer look at what HTML elements we have used for our To-Do list mock-up.

We have used a list with an id of “todolist” which contains To-Do items. Each item has custom data attribute named “data-worktype“, “data-desc“, etc which indicates the category what type of work item belongs to and other details of the item we want to store. We have also added a “Remove”  hyperlink at the end of each To-Do item so that we can tell jQuery to remove the item when we click on it.

The HTML form element contains a sample form with 4 fields for us to add a new To-Do item to our list. Our form contains a drop-down list which allows the user to select which category the new To-Do item should have. The input fields also consist of a description and start time field which we can display as details when the user clicks on a To-Do item. We will explore how we can program jQuery to add a new item along with the population of values to the item custom attributes.

Getting the Input from the User

To add a new item, we need to program jQuery to listen and respond to our button click event. Upon button click, jQuery should get all our input fields and insert them into our list.

First, let’s insert some code to get jQuery to listen to our button press.

We have learned how to listen to button presses previously. In the code above, we asked jQuery to listen to the “clicked” event on the button with the id additem“.

Next, we will need to get all the values of all the input fields in the form. The code is shown below:

In the above code, we have added 4 variables and assigned them to the values that the user entered in the input form. The new piece of code which you might not have seen before would be the value assignment for “category“. Let’s take a closer look at the code below:

This line of code asks jQuery to look at the HTML element with the idworktypeselect“, which refers to our drop-down list and we are using another selector “option:selected” to ask jQuery to return the option that is selected within our list. This value refers to the “value” attribute in each of our list item i.e chore or learning.

Adding a New Item to Our List

After getting all the input fields, we now need to use the values and add code to create and add a new HTML element to our list. We will use the jQuery “append()” function to add a new HTML element to our list.

The code to append the new item to our list is shown below:

In our example above, we added a temporary variable named “stringToAdd” and concatenated the template of our To-Do item and the values that were entered from our input form.

Exercise 1: Implement the Code and Add an Item

Now that you have learned how to add an item, try out the code above! The completed solution at this point can be accessed here.

Notice after you press the “Add Item” button, your new item is appended to the list on your screen without the browser going back to the server to refresh or retrieve a new page!

Removing Items from Our List

What is a To-Do list without a remove item function? A longer and longer To-Do list which we do not want!

Each of our To-Do list items has a remove link at the end of it. We will now whip up some code to remove the respective line when the remove link is clicked.

First, we will need to ask jQuery to listen to all the remove link clicks. The code to get jQuery to respond when the user clicks on the “Remove” link is shown below:

Let’s take a closer look at the code block above. In the code block, we are asking jQuery to listen on our To-Do list which has an id of todolist” and we want it to listen for “click” events on any links that are clicked inside that list. Therefore, the first argument in the function is the “click” event and the second argument is “a“, which refers to all the hyperlinks.

Next, we want to get jQuery to respond when the user clicks on the “Remove” link. jQuery should know which item the user has selected to remove from the list.

The code is shown below for this action:

Let’s examine the code that we have put in place to handle the removal of items. The “this” object refers to the element which the user has clicked. jQuery will detect which item was clicked and will map the “this” object to the HTML element that was clicked.

The “parent()” function will refer to the enclosing HTML element that encloses the HTML element that was clicked. Can you guess from our code above, which does the parent HTML element refers to?

Yes! If you have guessed that the parent element is the “li” element, you are correct!

Using the code above, we have essentially asked jQuery to detect which “Remove” hyperlink was clicked and get the list item that is associated with the clicked hyperlink and finally call the “remove()” function to remove it from the page.

All these are done without refreshing or reloading the page.

Exercise 2: Clean up the Code

Now that we have learned how to add and remove To-Do items from our list, let’s tidy up our HTML code and remove those placeholder elements when we first started.

The end result on our page should only consist of the list without items and our form to add a new item.

Try it yourself first before referring to the solution. If you are stuck or need a reference answer to compare with, the HTML code is listed below:

Showing More Details

So far, our To-Do list allows the user to add and remove items from it. Recall that we also have additional fields like description and start time of each of the tasks. We are going to add a panel where the additional details can be shown when the user selects a particular To-Do item.

We are going to use the same knowledge we have learned in our last tutorial by using radio buttons for each of the items which the user will choose and upon selection, show the details of the chosen item.

First, we are going to add a radio button to all of our task items. We will add it to the jQuery code where we have coded the function to add a new item.

The modified “stringToAdd” template looks like this:

If we add a new item now, the list items will look like this:

Listening to the Selected Item

We will now add a panel to show the details of the selected item. We can add a panel at the bottom of the list to show more details of the item. The details of the item should be values that are stored in the item’s data attribute i.e “data-worktype” which shows the category, “data-desc” which gives us the description of the task and “data-start” which shows us the start date that is entered for the task.

Do you remember how to get the value from the data attribute in the HTML element? Yes, we can extract the values using jQuery “.attr()” function.

First, we will modify our HTML to add a detail panel like so:

Exercise 3: Listen to the Selected Radio Button and Display Item Detail

In this exercise, you will need to accomplish the following:

  • Add jQuery code to listen to all radio button selections in the list

  • Upon selection, extract the data attributes and display them in the span placeholders in our detail panel

Do try out this exercise before referring to the solution below. Coding is best learned by the repetition and the application of concepts and knowledge.

Manage to get your code working? If not, you can refer to the solution.

First, we will add a listener to our “todolist” HTML element just like before, but this time we want it to listen to radio button changes.

Next, we will tell jQuery to extract the data attributes on the chosen task item and finally, we want to display the values on the span placeholders which we have added earlier. Our function then becomes like this:

Challenge: Add Category Filter Buttons

For this exercise challenge, your task is to add 3 buttons to filter the category types. Currently, there are 2 categories for each of the task items, i.e “Chore” and “Learning“. Your challenge therefore, is to:

  1. Add 3 buttons labeled “Chore“, “Learning” and “All” to the HTML code.

  2. Add jQuery code to handle the click event of this 2 buttons.

  3. Upon clicking on the button, only the items that belong to the category for which the button is clicked, will be displayed. For example, if the user clicks on the “Chore” button, only the task items in which category are “Chore” will be displayed. Similar functionality to be implemented for the “Learning” button.

  4. If the user clicks on the “All” button, all the task items are to be displayed.

The completed solution is here

Well done on completing this part 3 of our jQuery tutorial series!

In the next tutorial, we will learn how to query an online web service and store data in your local web browser.

CategoriesTags

Related Posts