2

I have a relatively simple code, I am annding event listeners in a loop, but the loop variable is not available when mapping the results.

for (let index = 0; index < 2; ++index) {
    $("#id" + index).on("keyup", function () {

        $.ajax({
                type: "GET",
                url: "https://some-url.com",
                dataType: "json",
                success: function (data) {
                    $('#div' + index).append(
                        $.map(data, function (myData, index) {
                            return '<a href="#" onclick="selectId(index, myData.id);"> Click me </a>'
                        }).join());
                }
            }
        );
    });
}

The result is: Uncaught ReferenceError: index is not defined

Edit: if I just use myData.id for example, everything works like a charm Any ideas what am I missing here?

4
  • 1
    When do you get that result? Commented Oct 28, 2020 at 14:18
  • because '<a href="#" onclick="selectId(index, myData.id);"> Click me </a>' generates a string with no reference to index. When rendered, it is looking for a global variable index Commented Oct 28, 2020 at 14:24
  • "selectId(index, myData.id)" -> "selectId(" + index + ", " + myData.id + ")" assuming id is an integer. Or use string interpolation stackoverflow.com/a/35984254/2181514 Commented Oct 28, 2020 at 14:25
  • if I just use myData.id for example, everything works like a charm Commented Oct 28, 2020 at 17:05

1 Answer 1

1

You are generating strings of HTML with embedded JS. The JS won't be evaluated until it is inserted in the document. That's a different scope with no index or myData variables.

Generate a jQuery object instead. And if you don't want to link anywhere, don't use a link!

 function (myData, index) {
     const $button = $("<button />")
     $button.text("Click me");
     $button.on("click", () => selectId(index, myData.id));
     return $button;
 }

(And don't join the array into a string, just append the array of jQuery elements).

Sign up to request clarification or add additional context in comments.

1 Comment

if I just use myData.id for example, everything works like a charm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.