如何在页面刷新时保留无线电输入状态

How to retain radio input state on page refresh

本文关键字:保留 无线电 输入 状态 刷新      更新时间:2023-09-26

我有一个表单,如果用户提交表单有错误(以防页面刷新),我需要在其上存储所有单选按钮的状态。

我想实现与此非常相似的东西:

$(function(){
        $('.example input[type="radio"]:checked').each(function(){
        $(this).attr("checked",true);
    });

任何帮助将不胜感激!

您可以将它的状态存储在本地存储中,并在每次页面加载后还原它。

关于存储值的小例子:

$('#myCheckbox').click(function () {
    localStorage['my.checkbox'] = this.checked;
});

恢复它:

$('#myCheckbox').prop('checked', localStorage['my.checkbox'] == 'true');

也许您将信息存储在会话令牌或会话 cookie 中。如果使用 html5 组件,则可以尝试使用 html 本地存储。

你只需要更新代码

$(function(){
        $('.example input[type="radio"]').each(function(){
           $(this).attr("checked",$(this).checked());
    });

它将保存单选按钮的属性,因为用户已为单选按钮选择。