Search code examples
javascriptvariablesprototype

Variable scope in onclick attribute with JavaScript


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-around.


Solution

  • 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'});
    }