I’m working on a form where users need the ability to dynamically add or remove input fields based on their actions. Specifically, I want to create a form that starts with one input field and allows users to add new input fields by clicking an "Add Input" button, and remove the last added input field by clicking a "Remove Input" button.
I’ve tried using JavaScript to add and remove the input fields, but I’m not sure if I’m doing it correctly or if there’s a more efficient way to handle this. Below is the HTML and JavaScript code I’ve written so far.
const addButton = document.getElementById('addInput');
const removeButton = document.getElementById('removeInput');
const inputContainer = document.getElementById('inputContainer');
addButton.addEventListener('click', function() {
const newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = 'inputField[]';
inputContainer.appendChild(newInput);
});
removeButton.addEventListener('click', function() {
const inputs = inputContainer.getElementsByTagName('input');
if (inputs.length > 1) {
inputContainer.removeChild(inputs[inputs.length - 1]);
} else {
alert('At least one input field is required!');
}
});
<form id="dynamicForm">
<div id="inputContainer">
<input type="text" name="inputField[]">
</div>
<button type="button" id="addInput">Add Input</button>
<button type="button" id="removeInput">Remove Input</button>
</form>
2
Answers
Your HTML and JS are correct. Did you forget the
<script>
and</script>
tags needed around the JS?I will suggest that you create a remove button for each input. Try not to use id’s for elements — they have to be unique, and are not really needed in forms, because form fields can be referred by name.