0

First let me explain you briefly what I'm trying to do, I have an unordered list with like 10 elements when the page first loads, then whenever the user scroll the list and reach the bottom it loads 10 more elements. I've done this with ajax and it works fine, the problem is that I want that the element clicked by the user has to appear in an input field and I don't know why this doesn't work:

function loadCod(){
$.ajax({
    url: '<%= request.getContextPath() %>/GetMoreCod',
    error: function(){
        var s = "CONNECTION'S ERROR";
        alert(s);
    },
    success: function(data){
        if(data == null) return null;
        if(data.indexOf('|') == -1) return new Array(buffer);
        var arrayCod = data.split('|');

        for(var i = 0; i< arrayCod.length; i++)
        {
            var ul = document.getElementById("menu");
            var li = document.createElement("li");
            $("li").each(function()
                {
                var $li = $(this);
                $li.css("cursor","pointer");       
            });
            var a = document.createElement("a");
            a.textContent = arrayCod[i];
            a.addEventListener("click",function(){  //HERE IS THE PROBLEM
            $("#codField").val(arrayCod[i]);},false); 
            li.appendChild(a);
            ul.appendChild(li);
        }

    },
    type: "GET"
});

}

Which is strange for me is if here $("#codField").val(arrayCod[i]) instead of arrayCod[i] I put something like "Hello" it does work and it appears in the input.

Another example is that if I write alert(arrayCod[i]) before the addEventListener it shows me the correct value but if I do this inside the addEventListener it shows me nothing.

[EDIT] I checked this but it still doesn't work

Community
  • 1
  • 1
Nurul
  • 1
  • 3
  • I think this is because when the event listener is triggered, the inside of that anonymous `function() {}` is in the global scope (on the document) whereas `arrayCod` is defined in the scope of the success function of the ajax call. What do you get if you put `console.log(this);` in the anonymous function? – Dr Rob Lang Jun 21 '16 at 09:33
  • 1
    Is this the exact code you test? Because if so then the console would tell you that there is a syntax error at `$("#codField").val(arrayCod[i)`. Something like `Uncaught SyntaxError: Unexpected token )` – t.niese Jun 21 '16 at 09:33
  • 3
    When your listener is called, i will be arrayCod.length and thus arrayCod[i] will be undefined. @RobLang - that is incorrect: arrayCod will be in scope because a function's scope is based on where it is *defined*. The value of `this` is separate to scope, and in this case should be the clicked element. – nnnnnn Jun 21 '16 at 09:35
  • Take a look at: [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – t.niese Jun 21 '16 at 09:36
  • `addEventListener` is a standard method and works properly. – Ram Jun 21 '16 at 09:37
  • if i write console.log(this); it gives me that: 150F24, 150F24 is the correct code. – Nurul Jun 21 '16 at 09:39
  • You have to use Javascript Closure here. a.addEventListener("click",function(i){ .................. }(i)); As addEvenListener is just for registering the event and the index i will have the last value. You have to pass the 'i' to the function using closure. – Shwetha Jun 21 '16 at 09:40
  • Change your code to this Closure: a.addEventListener("click",function(i){ $("#codField").val(arrayCod[i]); }(i),false); – Shwetha Jun 21 '16 at 09:44
  • @ShwethaU Doesn't work – Nurul Jun 21 '16 at 09:49
  • @t.niese could you re-open the thread please? I cheked the other thread but the problem still there – Nurul Jun 21 '16 at 10:24
  • @Nurul You need show how did try to apply a closure inside of the loop. As long as you don't show that there will be no reason to reopen, because the linked answer should solve the problem. – t.niese Jun 21 '16 at 10:28
  • @Nurul Use this closure syntax: (function(i){ a.addEventListener("click",function(){ $("#codField").val(arrayCod[i]);},false); })(i); – Shwetha Jun 21 '16 at 10:29
  • @ShwethaU Thanks a lot mate, it does work – Nurul Jun 21 '16 at 10:34
  • I am happy it wroked, please vote up my answer :) – Shwetha Jun 21 '16 at 10:55

0 Answers0