0

I have the following problem. I'm making an ajax request to an API which returns a json. I iterate through the json object and list the results in li tags the tricky part comes here when I make the li.OnClick() event I need to pass the current index of the selected item but i always get the last one. I think it's because it is passed by reference not by value. How can I cope with this problem?

Here is the code:

$StiboJQuery.ajax({
     url: loqateApiEndpoint,
     type: 'POST',
     data: { "lqtkey":"key", "query":street, "country":country },
     success: function(response) {
            debugger;
            if(response.Status === "OK" && response.output.length > 0)
            {
                 $StiboJQuery('#' + divId).remove();
                 var ul = document.createElement('ul');
                 var div = document.createElement('div');
                 div.id = divId;
                 div.className = 'address-suggestions';
                 for(var i = 0; i < response.output.length; i++)
                 {
                      var elNumber = [index: i];
                      var label = response.output[i];
                      var li = document.createElement('li');
                      li.setAttribute('Country', response.metadata[i].CountryName || '');
                      li.setAttribute('Street', response.metadata[i].DeliveryAddress || '');
                      li.setAttribute('City', response.metadata[i].Locality || '');
                      li.setAttribute('State', response.metadata[i].AdministrativeArea || '');
                      li.setAttribute('Postcode', response.metadata[i].PostalCode || '');
                      debugger;
                      li.innerHTML = response.output[i];

                      //Here is where I'm passing the i variable
                      li.onclick =  function() {
                          listItemClickEventHandler(this, div, isForBilling, i);
                       }
                       li.onmouseover = function(){
                          this.setAttribute("style", "background: #d7ebf9; padding: 3px 5px; cursor: pointer;");
                       }
                       li.onmouseout = function(){
                          this.setAttribute("style", "background: #fff; padding: 3px 5px;");
                       }
                        $StiboJQuery(ul).append(li);
                    }
                    $StiboJQuery(div).append(ul);
                    isForBilling ? $StiboJQuery("[id$='billingStreet']").after(div) : $StiboJQuery("[id$='shippingStreet']").after(div);
                }
            }
        });
    }
    function getCountry(isForBilling) {
        return isForBilling ? $StiboJQuery("[id$='billingCountry']").val() : $StiboJQuery("[id$='shippingCountry']").val();
    }
    function getStreet(isForBilling) {
        return isForBilling ? $StiboJQuery("[id$='billingStreet']").val() : $StiboJQuery("[id$='shippingStreet']").val();
    }

    function listItemClickEventHandler(sender, container, isForBilling, num) {
    debugger;
        var idPart = isForBilling ? 'billing' : 'shipping';
        var captureApiEndpoint = "https://api.everythinglocation.com/address/capture";
        var country = getCountry(isForBilling);
        var street = getStreet(isForBilling);

        // And here is where I use it and I always get the value of 10
        $StiboJQuery.ajax({
            url: captureApiEndpoint,
            type: 'POST',
            dataType: "xml",
            data: 
            {
                "lqtkey":"key",
                "query":street,
                "country":country,
                "result": num
            },
            success: function(response) {
            debugger;
                if(response.Status === "OK" && response.output.length > 0) {
                    var address = response.output;
                    console.log(address);
                }
            }
        });

        $StiboJQuery("[id$='"+idPart+"Country']").val(sender.getAttribute('Country'));
        $StiboJQuery("[id$='"+idPart+"Street']").val(sender.getAttribute('Street'));
        $StiboJQuery("[id$='"+idPart+"City']").val(sender.getAttribute('City'));
        $StiboJQuery("[id$='"+idPart+"State']").val(sender.getAttribute('State'));
        $StiboJQuery("[id$='"+idPart+"PostalCode']").val(sender.getAttribute('Postcode'));

        $StiboJQuery(container).remove();
    }
</script>
kritikaTalwar
  • 1,730
  • 1
  • 17
  • 25
Givko
  • 350
  • 2
  • 14
  • Where exactly is this `.output` defined or is it a property I never seen before? – zer00ne Jan 20 '17 at 08:11
  • The thing is that in the innerHtml I don't have the index, thus I need to pass it as a parameter I've tryed respone.output(li.innerHTML); but this always returns the last index. – Givko Jan 20 '17 at 08:12
  • the output is a property from the returned json :) – Givko Jan 20 '17 at 08:13
  • which property holds the list of elements – Givko Jan 20 '17 at 08:14
  • `$('li').on('click', function() {....` which delegates the 'click' event to any `
  • ` in the present or the future.
  • – zer00ne Jan 20 '17 at 08:17