jquery - Keep radio checked after submit ASP.NET Core
问题描述
I have several posts that I want to filter by category. I used the form below to do the filtering and this is done correctly, but after pressing the submit button, the checked radio button is not kept.
How can I keep the radio button checked using jQuery?
<form asp-controller="Requests" asp-action="Index" method="post">
@foreach (Category item in Model.Categories)
{
<div class="form-check">
<input type="radio" name="ID" id="ID" value="@item.ID" asp-for="@item.ID" class="form-check-input">
<label asp-for="@item.ID" class="form-check-label" for="examplecheck">@item.Name</label>
<input type="hidden" asp-for="@item.ID" />
</div>
}
<br />
<input type="submit" class="btn btn-outline-dark" value="Filter by category" id="filterByCategory">
</form>
解决方案
How can I keep the radio button checked using jQuery?
A workaround is that you could use localStorage
to store the <input>
clicked by the value attribute and then when the page is loaded, run the onclick
event of the right element.
<script>
$(function () {
$("input[type=\"radio\"]").click(function () {
var thisElem = $(this);
var value = thisElem.val();
localStorage.setItem("option", value);
});
var itemValue = localStorage.getItem("option");
if (itemValue !== null) {
$("input[value=\"" + itemValue + "\"]").click();
}
});
</script>
推荐阅读
- openlayers - 如何在 OpenLayers 5.3.0 中剪裁和显示剪裁的矢量几何图形
- python - “AttributeError:‘NoneType’对象没有属性‘get_text’”
- android - 通过移动设备上的 Facebook Native App 登录网络时,会话丢失
- .net - 如何在 dotnet dockerfile 中添加私有 nuget 源?
- java - 为什么要为 REQUEST 以外的 DispatcherType 编写 servlet 过滤器?
- c# - 如何通过脚本(Unity3d)为按钮文本加下划线和加粗
- java - Spring Security中的授权问题
- r - 为滑动窗口编写一个简单的循环
- javascript - 在函数和类组件之间反应`onClick`变化
- rxjs - 从 Effect 发送多个动作,在服务器响应上,在所有动作中使用 action.payload