Your HTML and JS are correct. Did you forget the <script>
and </script>
tags needed around the JS?
<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>
<script>
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!');
}
});
</script>