Exercise 4 - Dynamic Form
Exercise 4 - Dynamic Form
Objective: Develop a dynamic form where users can add input fields dynamically and submit the
form to gather all entered values.
Instructions:
The HTML structure consists of a <button> for adding new fields and a <form>
where these fields will be appended. Additionally, there is another button within the form
to submit the entered data.
2. JavaScript:
Write a function addField() that will be used to dynamically add new input fields
to the form:
1. Create a new input element using document.createElement('input') .
2. Then append this newly created input to the form using appendChild() .
Write a function submitForm() that will be responsible for gathering all entered
values from the input fields and ensuring they are filled:
1. All input fields within the form will be selected using
document.querySelectorAll('#dynamicForm input') and stored in the
inputs variable.
2. Set a flag allFilled to true initially, which will help you check if all fields are
filled later.
3. Iterate through each input field using the forEach loop.
For each input field, if the input doesn't have a value, set allFilled to
false .
Now append each input's value to the message string.
4. After the loop, check the allFilled flag:
If it's false, alert the user to fill all fields.
If it's true, display an alert showing all the gathered values.
3. HTML:
4. User Interaction:
Clicking the "Add Field" button should create a new input field in the form.
Filling in some data and clicking the "Submit" button should either alert the user to fill all
fields or show an alert with all the values separated by a comma.