views:

545

answers:

3

Hi, I'm using Prototype and trying to dynamically access a variable in a loop.

Code speaks better than me :

for (var i=0;i<5;i++) {
    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$('parent' + i).remove()" />', {position: 'after'});
}

The problem is that "i is not defined" when I click on any of the Cancel buttons.

How do I change the variable scope so that "i" keeps the proper value for each button ? I'm not interested in any work arroud.

+2  A: 

You can do it like this -

for (var i = 0; i < 5; i++) {

    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'});
}

It will be rendered like this -

<input type="button" value="Cancel" onclick="$('parent1').remove()" />
<input type="button" value="Cancel" onclick="$('parent2').remove()" />
<input type="button" value="Cancel" onclick="$('parent3').remove()" />
...

and so on.

Kirtan
+2  A: 

I think you were putting i into the quoted string instead of parent so it was at the wrong level of scope (conceptually speaking).

for (var i=0;i<5;i++)
{
    $('parent' + i).insert(
      '<input type="button" value="Cancel" onclick="$(\'parent' + i +
         '\').remove()" />', {position: 'after'});
}
1800 INFORMATION
Don't we have to add a ' while doing $('parent1') for Prototype? He'll have to escape it using \'.
Kirtan
yeah I think you are right
1800 INFORMATION
+1  A: 

you don't need that i variable. if you want to remove parent of that input, do:

<input type="button" value="Cancel" onclick="this.parentNode.parentNode.removeChild(this.parentNode)" />

or if you really really want, you can:

for (var i=0;i<5;i++) {
    $('parent' + i).insert('<input type="button" value="Cancel" onclick="$(\'parent' + i + '\').remove()" />', {position: 'after'});
}
skrat