简体   繁体   English

页面刷新后如何保留输入单选按钮的状态

[英]How to retain the state of input radio button after page refresh

I have a form on which there are 20 radio buttons. 我有一个表格,上面有20个单选按钮。 I need to store the state of the radio buttons if there are errors on the page(whereby page would refresh). 如果页面上有错误,我需要存储单选按钮的状态(从而刷新页面)。 I managed to get it working 50%. 我设法使其工作50%。 However, if i select different radio buttons on the second refresh, it would still retain the sate of the first submit. 但是,如果我在第二次刷新时选择了不同的单选按钮,它将仍然保留第一次提交的状态。

Here is my code: 这是我的代码:

var x= $("input[id^='question-']");
  $(x).click(function(){
    localStorage['radios'] = this.checked;
  });

  $(x).prop('checked', localStorage['radios'] == 'true');

Any help would much be appreciated! 任何帮助将不胜感激!

I think the unique form of getting the values after refreshing the page is send the information with POST or GET, after sending the form. 我认为刷新页面后获取值的唯一形式是在发送表单后使用POST或GET发送信息。 It's recomendable using PHP script to process the form, and make validations. 推荐使用PHP脚本处理表单并进行验证。

If you have any doubt, you can see here how to catch information of the forms 如果您有任何疑问,可以在这里查看如何获取表格信息

Your code looks like its just overwriting the same value again and again regardless of what input it's for, and also should use the change event rather than click. 您的代码看起来像是一次又一次覆盖相同的值,而不管它是为什么输入输入的,并且还应该使用change事件而不是click。 Try something like (untested): 尝试类似(未试用)的方法:

var $x = $("input[id^='question-']");

// Set localstorage on change event per radio button
$x.on('change', function(){
    localStorage[$(this).attr('name')] = this.checked;
});

// Check all radio buttons on page load against localStorage
$x.each(function(){
    $(this).prop('checked', localStorage[$(this).attr('name')] == 'true');
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM