简体   繁体   中英

How to keep the checkbox status after refreshing the page

I already looked at the other threads but couldn't find anything. I have one checkbox which hides some table columns by changing it's status but after every refresh it changes to the initial status (checked) and the columns aren't hidden anymore. Is there any way to keep the status after the refresh? Can I apply local storage in this case and is there a way to do it without jQuery? Below is some code:

EDIT: added the suggested function for localstorage

<script type="text/javascript">
function hide_show_table(col_name)
{
 var checkbox_val=document.getElementById(col_name).value;
 if(checkbox_val=="hide")
 {
  var all_col=document.getElementsByClassName(col_name);
  for(var i=0;i<all_col.length;i++)
  {
   all_col[i].style.display="none";
  }
  document.getElementById(col_name+"_head").style.display="none";
  document.getElementById(col_name).value="show";
 }

 else
 {
  var all_col=document.getElementsByClassName(col_name);
  for(var i=0;i<all_col.length;i++)
  {
   all_col[i].style.display="table-cell";
  }
  document.getElementById(col_name+"_head").style.display="table-cell";
  document.getElementById(col_name).value="hide";
 }
}
</script>

<script>
window.onload = function() {
  const checkbox = document.getElementById('fdt_col');
  checkbox.checked = !!localStorage.getItem('checked');
  checkbox.addEventListener('change', function(){
localStorage.setItem('checked', this.checked);});
}
</script>


echo"<input type='checkbox' name='fdt_col' value='hide' id='fdt_col'
onchange='hide_show_table(this.id);' checked>some text</input><br/>";

Thank you

I see you're using Vanilla javascript so you can use the localStorage like so:

window.onload = function() {
  const checkbox = document.getElementById('fdt_col');
  checkbox.checked = !!localStorage.getItem('checked');
  checkbox.addEventListener('change', function() {localStorage.setItem('checked', this.checked);});

}

Note about localStorage vs sessionStorage

localStorage will save your items on all tabs while sessionStorage is to be used if you need separation between tabs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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