Jan Bildus
Jan Bildus

Reputation: 57

Javascript for loop variable not working

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>";

Upvotes: 2

Views: 479

Answers (3)

nkotsioris
nkotsioris

Reputation: 3

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>';

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

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 + ");' >"

Upvotes: 5

MrCode
MrCode

Reputation: 64526

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 + ");' >"+
//                                           ^^^^^^^^^

Upvotes: 4

Related Questions