Friday, May 6, 2011

Variable scope in onclick attribute with Javascript

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.

From stackoverflow
  • 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.

  • 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'});
    }
    
    Kirtan : Don't we have to add a ' while doing $('parent1') for Prototype? He'll have to escape it using \'.
    1800 INFORMATION : yeah I think you are right
  • 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'});
    }
    

0 comments:

Post a Comment