刷新页面后保持选中复选框

时间:2020-05-29 04:13:06

标签: javascript jquery checkbox local-storage

我的Rails应用程序中具有以下复选框

<% if field["field_type"] == "checklist"%>
 <% templat = @custom_templates.select{|s| s["id"] == m["startup_field_template_id"]}.first%>
 <small>
   <% vals = field["options"].to_s.gsub(/[\[\"\]]/, '').split(',') %>
   <% vals.each do |v| %>
   <% if templat["option_multi"]%>
     <input type="checkbox" />&nbsp;&nbsp;&nbsp; <%= v %><br/>
   <% else %>
     <input type="checkbox" class="check" />&nbsp;&nbsp;&nbsp; <%= v %><br/>
   <% end %>
   <% end %>
 </small>
<% else %>
 n/a
<% end %>

我使用下面的代码在刷新页面后保持选中状态为选中状态

<sript>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>

但是刷新页面后,它会选中所有复选框。我该如何解决?

1 个答案:

答案 0 :(得分:1)

您使用的选择器将设置所有复选框的输入状态,因此您必须为每个输入分别设置checked属性,也不是使用localStorage的更好方法是使用setItemgetItem()种方法:

这是一个代码段(由于使用沙箱检查小提琴,因此在这里不起作用)和一个fiddle

$(function(){
  var test = localStorage.input === 'true'? true: false;
  $('input').each(function(i, el) {
   //console.log(localStorage.input);
   test = (localStorage.getItem(`input-${i}`) === 'true') ? true: false;
  	$(el).prop('checked', test || false);
  }); 
  
});
$('input').on('change', function() {
    localStorage.setItem(`input-${$(this).index('input')}`, $(this).is(':checked'));
  });
<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox