Add and Remove HTML Input Fields Dynamically using jQuery

If you are looking for a way to let your users dynamically add and remove multiple input fields in your HTML forms using jQuery, follow this tutorial.

It is useful in scenarios where you would require users to enter multiple answers for a single question; for instance, you have a job application form in which users can enter multiple qualifications by adding the input field dynamically instead of giving them a fixed number of input fields.

HTML

Add something like below to your HTML form, you can change the name of your input fields as per your needs.

Div with the id "items" is where we would add our input fields.

<div class='item'>
    <input type="text" name="items[]" placeholder="Enter Something">
    <button id="add">Add +</button>
</div>
<div id="items">
</div>

JS

$(document).ready(() => {
  let template = `<div class='item'>
    <input type="text" name="items[]" placeholder="Enter Something" />
    <button class="remove">X</button>
    </div>`;

  $("#add").on("click", () => {
    $("#items").append(template);
  });
  $("body").on("click", ".remove", (e) => {
    $(e.target).parent("div").remove();
  });
});

Adding a Limit

Basically, we will maintain a global variable that increases when users add input fields and decreases when users remove input fields.

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

  $("#add").on("click", () => {
    if (i >= 10) {
      alert("Maximum Limit Reached");
    } else {
      ++i;
      $("#items").append(template);
    }
  });
  $("body").on("click", ".remove", (e) => {
    --i;
    $(e.target).parent("div").remove();
  });
});

CSS

a sample CSS code to style your elements.

.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;
}