0
function listeners(){
    validation = new Validator();
    for(input in inputs){
        el = $("#"+input+"");
        addEvent(el, "input", function(){
            inputs[input].value = el.value;
            if(validation.fails(inputs[input])){
                //Do something
            }

        })
    }
}

Hi guys, i have three inputs {name, email, comment}, and i want to attach an event listener and make some validation to every input. The above code works but it returns always the last input(comment). Please, is there any solution to solve this problem? I thought about callback, but i didn't know how to implement it in this context.

Bharata
  • 13,509
  • 6
  • 36
  • 50
Redzoua
  • 23
  • 4
  • What is `addEvent`? That should be throwing a syntax error, unless you defined it elsewhere. Are you sure you don't mean [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener)? – General_Twyckenham Jan 14 '18 at 22:39
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). When any of your event listeners are called. The value of `input` will be the last input. Use `let input in inputs` or event delegation. – Sebastian Simon Jan 14 '18 at 22:40
  • @General_Twyckenham, Yes it's defined. – Redzoua Jan 14 '18 at 22:42

1 Answers1

0

I solved the problem by changing my code to this:

function listeners(){
    validation = new Validator();
    for(input in inputs){
        var el = $("#"+input+"");
        var i = inputs[input];
        (function(input, e){
            addEvent(e, "input", function(){
                data[input] = input.value = e.value;
                if(validation.fails(input)){
                    //Do something
                }
            })
        })(i, el)

    }
}   
Redzoua
  • 23
  • 4