Jacek Pietal
Jacek Pietal

Reputation: 2019

Passing parameters to onchange doesnt use the parameters at runtime

Hello I am using function

function prepareRadios(radioGroupName) {
  var radios = document.getElementsByName(radioGroupName);
  for( i = 0; i < radios.length; i++ ) {
    document.getElementById(radios[i].id).onchange = function() {
      radioUpdated(radioGroupName, radios[i].id); 
    };
  }
}

the problem is, that the onchange event fires with quote (radioGroupName, radios[i].id) instead of having those values put into it with my function

I need to pass the VALUES of them, not the names of the vars

What am I doing wrong?

Upvotes: 0

Views: 141

Answers (1)

Andreas
Andreas

Reputation: 21881

It's closure-time :)

function prepareRadios(radioGroupName) {
    var radios = document.getElementsByName(radioGroupName);
    for( i = 0; i < radios.length; i++ ) {
        document.getElementById(radios[i].id).onchange = (function(name, id) {
            return function() { radioUpdated(name, id); }
        })(radioGroupName, radios[i].id);
    }
}

Upvotes: 2

Related Questions