need revision of code (checkbox, cookie, array)
Hello,
just started with jQuery and would like to ask some expert for help to
revise my code.
Script is working just fine but I am bit worried about my amateur
code, think could be better..
Project problem: maintain state of checkboxes in a paginated datagrid
(selecting diff products for comparison)
Since using classic ASP needed help of jQuery.
My solution: when select checbox beside each product write a cookie
(PID) which holds array of product ID's (154+332+...) also cookie CID
for products group category (eg. 3). Each time page loads script
checks cookie which chekboxes should put in state on. Also use images
which replace chekboxes (on/off).
Code:
// check cookie and put right checkbox state--------------------------
$(document).ready(function(){
$(".compareCheck").each(function() {
var img = "off";
if ($.cookie('PID')) {
var ca = $.cookie('PID').split("+");
for(var i=0;i < ca.length;i++)
{ var c = ca[i];
if (c == $(this).val()){
img="on"}
}}
$(this).replaceWith('<img src="img/template/checkbox-'+ img+'.gif"
class="compare" style="cursor:pointer;" id="'+ $(this).val() +'" />');
}); });
// write
cookie----------------------------------------------------------------------
$(function() {
$(".compare").click(function() {
var ID = $(this).attr("id");
if ($.cookie('CID') != '<%=cDescValueID%>')
{ $.cookie('PID', ID, { path: '/', expires: '1' });
$.cookie('CID', '<%=cDescValueID%>', { path: '/', expires: '1' });
$(this).replaceWith('<img src="img/template/checkbox-on.gif" id="'+ ID
+'" alt="Product is in compare list"/>');
return false;
} else {
var oldcookie = $.cookie('PID') + '+';
var number;
var ca = $.cookie('PID').split("+");
for(var i=0;i < ca.length;i++)
{ var c = ca[i];
if (c == ID){
ID="";
oldcookie = $.cookie('PID');}
}
if (i>4 ){alert("MAX number of products to compare!");}
else {$.cookie('PID', oldcookie+ID, { path: '/', expires: '1' });
$(this).replaceWith('<img src="img/template/checkbox-on.gif" id="'+ ID
+'" />');
return false;
};};
});
});