
Introduction
Creating input text fields dynamically can be useful for forms that require variable input fields, such as adding multiple entries without refreshing the page. This guide demonstrates how to achieve this using JavaScript and jQuery.
✅ Step 1: Set Up the Basic HTML Structure
Create a container for the input fields and a button to add new inputs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Input Fields</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h2>Dynamic Input Fields</h2>
<div id="inputContainer">
<input type="text" name="inputField[]" placeholder="Enter text">
</div>
<button id="addInput">Add Input</button>
</body>
</html>
✅ Step 2: Add JavaScript for Dynamic Input Creation
$(document).ready(function() {
$('#addInput').click(function() {
$('#inputContainer').append('<input type="text" name="inputField[]" placeholder="Enter text">');
});
});
✅ Step 3: Optional - Remove Input Fields
If you want to remove input fields, you can modify the script as follows:
$(document).ready(function() {
$('#addInput').click(function() {
$('#inputContainer').append('<div class="input-group"><input type="text" name="inputField[]" placeholder="Enter text"><button class="removeInput">Remove</button></div>');
});
$(document).on('click', '.removeInput', function() {
$(this).parent().remove();
});
});
✅ Step 4: Styling (Optional)
Add some CSS for better user experience.
.input-group {
margin-bottom: 10px;
}
.removeInput {
margin-left: 10px;
}
Conclusion
By using jQuery, you can easily create input text fields dynamically. This approach is beneficial for forms with variable input needs and enhances the user experience.