Add / Remove HTML Input Fields Dynamically in Vanilla JS

Creating dynamic input boxes in HTML using plain JavaScript, HTML and CSS This can be helpful in cases where you have to give optional fields for your users to add.

In web development, dynamic item lists allow users to add or remove items on the fly, providing a more interactive user experience.

This blog will explain step-by-step how to create a dynamic item list using JavaScript. We will break down the provided code into segments, explaining the HTML structure and the JavaScript functionality.

If you want the jQuery version of the same functionality, checkout this article: Add and Remove HTML Input Fields Dynamically using jQuery

HTML Structure

The first segment of the code snippet presents the HTML structure for the dynamic item list. Let's examine the HTML elements:

<div class='item'>
    <input type="text" name="items[]" placeholder="Enter Something">
    <button id="add">Add +</button>
</div>
<div id="items">
</div>
  • <div class='item'>: This div represents a single item in the list. It contains an input field and a button to add new items.
  • <input type="text" name="items[]" placeholder="Enter Something">: This input field allows users to enter content for each item. The name attribute is set as "items[]" to capture the values when the form is submitted.
  • <button id="add">Add +</button>: This button has the id "add" and serves as the "Add" button for adding new items to the list.
  • <div id="items">: This empty div will serve as the container for the dynamically added items.

JavaScript

The second segment of the code snippet contains the JavaScript code responsible for the dynamic behavior of the item list. Let's break it down step by step:

window.addEventListener("DOMContentLoaded", () => {
  let i = 1;
  let template = `<div class='item'><input type="text" name="items[]" placeholder="Enter Something" /><button class="remove">X</button></div>`;
  let add = document.getElementById("add");
  let items = document.getElementById("items");

  add.addEventListener("click", () => {
    if (i >= 10) {
      alert("Maximum Limit Reached");
    } else {
      ++i;
      items.innerHTML += template;
    }
  });

  document.body.addEventListener("click", (e) => {
    const target = e.target;
    if (target.classList.contains("remove")) {
      target.parentNode.remove();
    }
  });
});
  • window.addEventListener("DOMContentLoaded", () => { ... }): This event listener waits for the HTML document to be fully loaded before executing the JavaScript code inside.
  • let i = 1;: This variable `i` represents the current count of items in the list and is initialized with a value of 1.
  • let template = `...``;: This variable stores an HTML template string representing the structure of each dynamically added item. It contains an input field and a remove button.
  • let add = document.getElementById("add");: This line retrieves the element with the id "add" and assigns it to the variable add.
  • let items = document.getElementById("items");: This line retrieves the element with the id "items" and assigns it to the variable `items`, which will serve as the container for the dynamically added items.
  • The add.addEventListener("click", () => { ... }) function attaches a click event listener to the "Add" button.
  • Inside the event handler, the code checks if the current count of items (`i`) has reached the maximum limit of 10. If it has, an alert is displayed with the message "Maximum Limit Reached".
  • Otherwise, the count is incremented by one (`++i`), and the HTML template stored in the `template` variable is appended to the `items` container using `items.innerHTML += template`. This effectively adds a new item to the list.
  • The document.body.addEventListener("click", (e) => { ... }) function attaches a click event listener to the body of the document. This delegated event handler listens for clicks on any element within the body.
  • Inside the event handler, the code checks if the clicked element has the class "remove" using target.classList.contains("remove").
  • If the condition is true, it removes the parent node of the clicked element using target.parentNode.remove(). This removes the entire item from the list.

CSS

Finally, let's add some CSS to make it look pretty.

.item{
	margin-bottom: 5px;
}
.item input{
padding: 5px 10px;
border: 0;
border-radius: 4px;
box-shadow: 0 0 2px #00000094;
}
.item button {
cursor: pointer;
padding: 5px 8px;
border: 0;
border-radius: 5px;
margin-left: 5px;
background: #df5454;
color: #fff;
}
.item #add {
	background: #61af49;
}