shep shep - 1 month ago 5
Javascript Question

Simple javascript onClick for table data

I have a table of images in rows of 10 and I'm trying show the id of each image when I click on it. I've tried many, many different ways of this (code below) but no joy. Hopefully someone can set me straight. No point in any jquery or other clever stuff though - I don't understand it yet. Just some simple pointers would help a lot. Thanks

document.writeln('<table border = 1 >');

for (var j = 0; j < myArray.length; j++){
if (j % 10 == 0 && j !== 0){
document.writeln('</tr><tr>');
}

document.writeln('<td ><img id = "' + myArray[j].id + '" src="' + myArray[j].src + '" onclick = selectImage() /></td>');
}

document.writeln('</tr></table>');

function selectImage() {
alert(document.getElementById(id));
}

Answer

when making a call to selectImage, try passing the current image element by using the 'this' keyword i.e selectImage(this)

and then in the script, you can receive the passed object and retrieve the id attribute from there.

function selectImage(obj)
{
alert(obj.id);
}
Comments