Dynamic Input Box Management
November 16, 2024 ยท AI Conversations
### HTML
<div id="dynamic-inputs">
<div class="input-group">
<input type="text" name="inputs[]" class="form-control" placeholder="Enter value" required>
<button type="button" class="btn btn-danger remove-input">Remove</button>
</div>
<div class="input-group">
<input type="text" name="inputs[]" class="form-control" placeholder="Enter value" required>
<button type="button" class="btn btn-danger remove-input">Remove</button>
</div>
<div class="input-group">
<input type="text" name="inputs[]" class="form-control" placeholder="Enter value" required>
<button type="button" class="btn btn-danger remove-input">Remove</button>
</div>
</div>
<button type="button" id="add-input" class="btn btn-primary">Add New Input</button>
<!-- jQuery (Make sure to include this in your HTML file) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
### jQuery Script
$(document).ready(function () {
// Set the minimum number of input boxes
const minInputs = 3;
// Function to check and toggle the remove button
function toggleRemoveButtons() {
$('.remove-input').prop('disabled', $('.input-group').length <= minInputs);
}
// Initialize the remove button visibility
toggleRemoveButtons();
// Add new input box
$('#add-input').click(function () {
$('#dynamic-inputs').append(`
<div class="input-group">
<input type="text" name="inputs[]" class="form-control" placeholder="Enter value" required>
<button type="button" class="btn btn-danger remove-input">Remove</button>
</div>
`);
toggleRemoveButtons();
});
// Remove input box
$('#dynamic-inputs').on('click', '.remove-input', function () {
$(this).parent('.input-group').remove();
toggleRemoveButtons();
});
});
### Explanation
1. **HTML Structure**:
– We start with 3 input boxes.
– Each input box has a "Remove" button.
– A "Add New Input" button allows adding more input fields.
2. **jQuery Logic**:
– `minInputs` defines the minimum number of input fields.
– `toggleRemoveButtons()` checks if there are more than the minimum required inputs; if not, the "Remove" button is disabled.
– The `#add-input` button adds a new input box dynamically.
– The `remove-input` button deletes the specific input box, but only if more than 3 input boxes remain.
### Key Features
– **Dynamic Addition**: Users can add as many input fields as needed.
– **Dynamic Removal**: Users can delete input fields but cannot go below the minimum of 3.
– **Validation**: Each input box is marked as `required`, ensuring it can't be empty when the form is submitted.
This solution provides a flexible and user-friendly interface with jQuery.