In my scenario, the resident registers the needed details for step one is resident details then the next step is addressing details the resident can multiply address. Now what if the resident mis click the add address button now my problem is how to remove the mis click address.
This is my UI
enter image description here
@model Registration
@{
ViewData["Title"] = "Register Page - Step Two";
}
<button type="button" class="btn btn-primary" onclick="addAddress()">Add Address</button>
<div class="container mt-5">
<div class="row">
<div class="col-md-12">
<h2 class="text-center mb-4">Address Details</h2>
<form asp-page-handler="RegisterStepTwo" method="post">
<div id="addressesContainer" class="row mt-3">
<!-- Addresses will be dynamically added here -->
</div>
<button type="submit" class="btn btn-primary w-100">Next</button>
</form>
</div>
</div>
</div>
@section Scripts {
<script>
let addressCount = 0;
function addAddress() {
addressCount++;
const addressesContainer = document.getElementById('addressesContainer');
const fieldHtml = `
<div class="col-md-3 mb-3">
<label class="form-label">Address type</label>
<select id="addressType${addressCount}" class="form-select">
<option value="">Select Address Type</option>
<option value="Permanent">Permanent</option>
<option value="Present">Present</option>
</select>
</div>
<div class="col-md-3 mb-3">
<label class="form-label">House No. ${addressCount}</label>
<input type="text" class="form-control" placeholder="Enter house number">
</div>
<div class="col-md-3 mb-3">
<label class="form-label">Street ${addressCount}</label>
<input type="text" class="form-control" placeholder="Enter street name">
</div>
<div class="col-md-3 mb-3">
<label class="form-label">Barangay ${addressCount}</label>
<input type="text" class="form-control" placeholder="Enter barangay name">
</div>
<div class="col-md-3 mb-3">
<button type="button" class="btn btn-danger remove-address-btn" data-remove-index="${addressCount}">Remove</button>
</div>
`;
addressesContainer.innerHTML += fieldHtml;
}
const removeButtons = document.querySelectorAll(`[data-remove-index="${addressCount}"]`);
removeButtons.forEach(button => {
button.addEventListener('click', () => removeAddress(addressCount));
});
function removeAddress(indexToRemove) {
const addressesContainer = document.getElementById('addressesContainer');
const elementsToRemove = document.querySelectorAll(`[data-remove-index="${indexToRemove}"]`);
elementsToRemove.forEach(element => {
const parentElement = element.closest('.col-md-3.mb-3');
if (parentElement) {
parentElement.remove();
}
});
}
// Initialize with one set of fields
addAddress();
</script>
}
New contributor
John Erick Cuizon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2