Blog>
Snippets

Dynamically Adding Form Inputs

Create a form where you can dynamically add new input fields for, say, a list of participants in a workshop. Include buttons to add and remove inputs, and handle state updates accordingly.
// HTML form element
const form = document.querySelector('#participants-form');

// Function to add an input field
function addInputField() {
  const newInput = document.createElement('input');
  newInput.type = 'text';
  newInput.name = 'participant';
  newInput.className = 'participant-input'; // Optional: for styling
  form.appendChild(newInput);
}

// Function to remove the last input field
function removeInputField() {
  const inputFields = document.querySelectorAll('.participant-input');
  if (inputFields.length > 1) {
    inputFields[inputFields.length - 1].remove();
  }
}

// Event listeners for the buttons
const addButton = document.querySelector('#add-participant-button');
addButton.addEventListener('click', addInputField);

const removeButton = document.querySelector('#remove-participant-button');
removeButton.addEventListener('click', removeInputField);
This code provides the JavaScript for handling the dynamic addition and removal of input fields in a form. It first selects the form element and provides two functions, addInputField and removeInputField, to add a new input field or remove the last input field respectively. It binds these functions to the click events of two buttons with the IDs 'add-participant-button' and 'remove-participant-button'.