Javascript Checkbox cookie

為{幸葍}努か 提交于 2020-01-05 10:06:23

问题


On my php form with random number of checkboxes (depends on MySQL query results) i use pagination and checkbox_cookie.js script to remember checkboxes values from other subpages.

It works well if there is less then 200 checkboxes after that it's loosing memory of last checkbox changes e.g. i have 230 checkboxes spllited in 8 subpages it remember positions for those in 7 sub-pages but can't save states of checkboxes at page 8.

And now i'm seriously out of clue why is it happening.

Is it cookie size? JSON array limit? Something? Perhaps you will know where to look for an aswer.

Here's the checkbox_cookie code:

var aa_checkbox;  

function init_checkbox(){  
//setup blank cb cookie  
if(!Cookie.read('cb')){  
Cookie.write('cb', JSON.encode({}));  
}  

//setup "associative array" to match what is currently in the cookie  
aa_checkbox = JSON.decode(Cookie.read('cb'));  


//set up each checkbox with class="remember_cb"  
$$('input.remember_cb').each(function(el){  

//mark checked if it is in the cookie  
if(aa_checkbox[el.name]){  
  el.checked = 'checked'  
}  

//setup onclick event to put checkbox status in the   
el.addEvent('change', function(){  
  if(el.checked){  
    aa_checkbox[el.name] = 1;
  }else{  
    delete(aa_checkbox[el.name]);
  }     
})  
})  

//save aa_checkbox back into cookie upon leaving a page  
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};  

setup_form();  

return true;  
 }  

function setup_form(){  
 //set up form so that it adds the inputs upon submit.  
$$('form.remember_cb_form').each(function(form){  
 form.addEvent('submit', function(ev){  
   //clean up previously inserted inputs  
   var aa_hidden_insert = $$('input.hidden_insert');  
    $each(aa_hidden_insert, function(el){   
     el.parentNode.removeChild(el);  
   })  

   var el_form = this;  

    //insert hidden elements representing the values stored in  aa_checkbox  
  $each(aa_checkbox, function(i_value, s_name){  
    if(i_value){   
      var el_input = document.createElement('input');  
      el_input.type = 'hidden';  
      el_input.value = i_value;  
      el_input.name = s_name;  
      el_input.setAttribute('class', 'hidden_insert');  
      el_form.appendChild(el_input);  
    }  
  });  
   });  
 });  
}  

window.addEvent('domready', init_checkbox); 

回答1:


Cookies have very small size limits since they get sent to server with each and every http request. You would be much better off using localStorage or sessionStorage API's. These store data within the browser itself

Although the localStorage API is fairly simple to use on it's own, there is a very handy little library wrapper you can use store.js which makes it even simpler

Reference : MDN STorage Docs



来源:https://stackoverflow.com/questions/31457033/javascript-checkbox-cookie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!