我有一个带有“重置”按钮的表单。但单击它后,它不会重置
select
标签帮助项。怎样才能用最实用又最简单的方式解决呢?
我正在使用 ASP.NET Core 7,这是我的
.cshtml
文件中的表单:
<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>
HTML 表单中的
type="reset"
按钮可将表单元素重置为其定义的初始值。然而,由 select
生成的 asp-items="Html.GetEnumSelectList<AgeCategoryEnum>()"
标签的项目并不直接由 HTML 属性控制。所以你可以使用 JavaScript 来重置 select 元素。
<button type="reset" class="btn btn-warning" onclick="resetForm()">
<i class="bi bi-repeat"></i>
reset
</button>
<script>
function resetForm() {
// Reset the form
document.getElementById('filter-form').reset();
// Reset the select element to its first option
document.querySelector('#filter-form select').selectedIndex = 0;
}
</script>