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