Step 1: HTML Structure
The HTML structure includes the form, a button to add new fields, and placeholders for each dynamically added field.
Key Features in This Code:
-
Adding New Fields:
-
The Add Employee button (
#btnAdd
) creates a new input field each time it is clicked. -
Each new input field has a unique identifier (
empName-1
,empName-2
, etc.) and a corresponding "Remove" button.
-
-
Removing Fields:
-
Each input field comes with a "Remove" button next to it, and when clicked, the associated input field is removed from the form.
-
-
Form Validation:
-
The form is validated using jQuery's
validate()
method. In this case, it ensures that the Employee Name is required. You can easily add more validation rules for the dynamically created input fields as needed.
-
-
Dynamic Field Indexing:
-
Each dynamically added input field is given a unique identifier using the counter
i
, which increments with every new field added.
-
How it Works:
-
When the user clicks the Add Employee button, a new input field (along with a remove button) is appended to the form.
-
The user can remove any added input field by clicking the Remove button next to it.
-
The form also provides validation for the fields using jQuery's
validate()
method, which ensures that the form data is correctly submitted.