2

I am having a problem with my for loop inside a javascript function. The variable i is not working as an argument for the function showAlbum(i). Why is that happening?

var out = "<table>";
for(i = 0; i < arr.length; i++) {
            out += "<tr><td><a href=''onclick='showAlbum(i);' >"+
                arr[i].artist +
                " - " +
                arr[i].title +
                "</a></td></tr>";
        }
out += "</table>";

3 Answers 3

5

Because i wrapped in quotations is the literal character i, not the value held within your i variable. You need to evaluate it outside of the quotations:

out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the short and well explained answer.
4

The i is within the string literal, so variables are not parsed from the string.

Break out of the string like so:

out += "<tr><td><a href=''onclick='showAlbum(" + i + ");' >"+
//                                           ^^^^^^^^^

Comments

0

Try changing the formatting to:

var i,
    out = '<table>';
for (i = 0; i < arr.length; i++) {
    out += '<tr><td><a href="" onclick="showAlbum(' + i + ')" >' +
        arr[i].artist +
        ' - ' +
        arr[i].title +
        '</a></td></tr>';
}
out += '</table>';

Comments

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.