...

View Full Version : select string + variable



hipolito
01-13-2012, 12:17 PM
Hi all,

I am having a hard time on this, can you help pls?
I have this code?

$("select[name=objeto"+contcheck+"]").change(function(){
$("select[name=titulo"+contcheck+"]").html('<option value="0">Carregando...</option>');

where contcheck is a counter, so a number.
It does not work at all, any help how to concatenate string and variable like this:
objeto1
objeto2
objeto3 .... and so on.

Thx.

devnull69
01-13-2012, 12:30 PM
The problem is a common one ... and I just recently described it here in a different context

You say contcheck is a counter. So you have some kind of a loop where you increase/decrease contcheck. In every loop you create a change listener for the respective select element. So far so good. With the callback of the change listener you create a CLOSURE. This closure is aware of the surrounding scope even if the code of the scope has already finished executing.

BUT: It is not aware of its scope from the time it was created but rather from the point of time it's executed. And by that time the counter will ALWAYS be on its value from the final loop.

Solution: Create an inner closure inside a self-calling anonymous function like this


var contcheck = ....
$(...).change((function(innerContcheck) {
return function() {
// you can access the correct "contcheck" here using innerContcheck
}
})(contcheck));

hipolito
01-13-2012, 01:43 PM
Hi Devnull69, thx for your reply.
Well, I dont really get what you just said, but here is my part of the code that I have trouble:
$("select[name=objeto"+contcheck+"]").change(function(){
$("select[name=titulo"+contcheck+"]").html('<option value="0">Carregando...</option>');

$.post("buscaTitulos.php",
{objeto:$(this).val()},
function(valor){
$("select[name=titulo"+contcheck+"]").html(valor);
}
)

});

contcheck++;

all I have to do is to concatenate "objeto" and "titulo" with contcheck, is that what you talked about?

devnull69
01-13-2012, 02:22 PM
Yes ... I can give you one more simple example



for (i=0; i<10; i++) {
// i counting from 0 to 9
// at the end of this loop, i will be 10 and the loop will end

// after 2 seconds start another action, and refer to i inside of this action
window.setTimeout(function() {
// here i will ALWAYS be 10, because the code of the scope has already
// reached the end of the loop after 2 seconds
alert(i);
}, 2000);
}


Solution


for (i=0; i<10; i++) {
// i counting from 0 to 9
// at the end of this loop, i will be 10 and the loop will end

// this time create an inner function
window.setTimeout((function(innerI) {
// here innerI will go from 0 to 9 as expected
return function() {
alert(innerI);
}
})(i), 2000);
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum