Where is the error in this code

Here is my snippt code. But the code breaks after the inner loop. But no error message. Any idea?

Thanks.

    var lastnames   = document.getElementsByClassName('box_nachname');
    var firstnames      = document.getElementsByClassName('box_vorname');
    var teilnehmer  = document.getElementsByClassName('select');
    observers = [];

    // iterate over nachname array.
    for (var i = 0; i < lastnames.length; i++) {

        // Create an observer instance.
        observers[i] = new Observer();


        // Subscribe oberser object.
        for(idx in teilnehmer) {
            if(teilnehmer[idx].id.split("_")[0].toLowerCase() !== "zl") {
                var anynum = function(element) {
                                             observers[i].subscribe(element, updateTeilnehmerSelectbox);
                                         }(teilnehmer[idx]);
            }
        }


        //on blur the Observer fire the updated info to all the subscribers.
        var anynumNachname = function(j, element, value, observer) {
                                            cic.addEvent(lastnames[j], 'blur', observer.fire(element, value));
                                            } (i, lastnames[i], lastnames[i].value, observers[i]);
        cic.addEvent(firstnames[i], 'blur', function(element, value, observer) {observer.fire(element, value)}(lastnames[i], lastnames[i].value, observers[i]));

    }

      

+2


a source to share


1 answer


You are using the loop variable "i" in the call to "addEvent". This will not work as expected because each of the event handlers will have the same "i" and therefore each will only see the last value that is set to "i".

cic.addEvent(firstnames[i], 'blur', (function(index) {
  return function(element, value, observer) {
    observer.fire(element, value)}(lastnames[index], lastnames[index].value, observers[index]);
  };
})(i));

      



Also, while I'm not sure if this is necessary, I would put the function you call for "anynumNachname" in parentheses:

var anynumNachname = (function(j, element, value, observer) {
  cic.addEvent(lastnames[j], 'blur', observer.fire(element, value));
})(i, lastnames[i], lastnames[i].value, observers[i]);

      

+2


a source







All Articles