首页 > 解决方案 > 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>

标签: jqueryasp.net-core

解决方案


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>

推荐阅读