Variable scope in onclick attribute with Javascript

I am using Prototype and am trying to dynamically access a variable in a loop.

The 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 scope of the variable so that "i" stores the correct value for each button? I am not interested in any work.

0


a source to share


3 answers


I think you were putting i

in the quoted string instead parent

, so it was at the wrong level of visibility (conceptually).



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

      

+2


a source


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 display 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()" />
...

      

etc.

+2


a source


you don't need the i variable. if you want to remove the parent of this input then follow these steps:

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

      

or if you really want it, you can:

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

      

+2


a source







All Articles