I have a form with a button with type "reset". But after clicking it, it doesn't reset the select
tag helper items. How can I solve it in the practical and easiest way?
I'm using ASP.NET Core 7 and this is the form inside my .cshtml
file:
<form asp-area="admin" asp-controller="course" asp-action="index" method="get" id="filter-form">
<input type="hidden" asp-for="PageIndex" />
<input type="hidden" asp-for="PageSize" />
<div class="mb-3">
<label class="form-label"> Title:</label>
<input asp-for="Title" class="form-control">
</div>
<div class="mb-3">
<label class="form-label"> Age Category:</label>
<select class="form-select" asp-for="AgeCategory" asp-items="Html.GetEnumSelectList<AgeCategoryEnum>()"></select>
</div>
<div class="modal-footer">
<button type="reset" class="btn btn-warning">
<i class="bi bi-repeat"></i>
reset
</button>
<button type="submit" class="btn btn-primary">Filter</button>
</div>
</form>
Edit:
When URL has no query params, the reset button works. (e.g. https://localhost:44331/admin/course). but when you have filtered the form once before and click the reset button, it doesn't work!(e.g. https://localhost:44331/admin/course?PageIndex=1&PageSize=10&AgeCategory=1)
Try to change the button type="reset"
to type="button"
like :
<button type="button" class="btn btn-warning" onclick="ResetFormWithJS()">
<i class="bi bi-repeat"></i>
reset
</button>
<script>
function ResetFormWithJS() {
document.getElementById("Title").value = "";// reset Title
document.querySelector('#filter-form select').selectedIndex = 0;// reset Select
}
</script>