I’m creating a jquery ui sortable with cookies to maintain the state when updated.
Here’s the important part of the code:
for(i=0; i<counter; i++) {
var connect = "";
var count = 0;
var tipo = "tipo" + i;
for(j=0; j<counter; j++) {
if(j != i) {
if(count > 0) {
connect = connect + ",.tipo" + j;
}
else {
connect = ".tipo" + j;
count++;
}
}
}
$( "." + tipo ).sortable({
connectWith: connect,
dropOnEmpty: "true",
opacity: 0.8
});
$(".tipo" + i).sortable({
activate: function(event, ui) {
var order = $( "." + tipo ).sortable('toArray');
createCookie(tipo, order, 1);
},
update: function(event, ui) {
var order = $( "." + tipo ).sortable('toArray');
createCookie(tipo, order, 1);
},
receive: function(event, ui) {
var order = $( "." + tipo ).sortable('toArray');
createCookie(tipo, order, 1);
}
});
}
The problem that I’ve is that var tipo = "tipo" + i; will become tipo2 in the last statement and all of the previous createCookie(tipo, order, 1); will have tipo as tipo2 instead of tipo0 or tipo1.
I hope you understand what I’m saying. If not, just tell me!
But, how can I make this have the right tipo?
What the article I linked to boils down to is that there is only one
tipobecause the variable exists in the same scope.forloops don’t create a new scope for each iteration.You need to freeze the variable in a new scope, which is only possible with functions in JavaScript. I also recommend using
varfor all variables (i.e. all your loop counters).