0

I am using following code to crete images programatically (dynamically in for loop):

function showImage(source, id) {
var list = document.getElementById("display-list");

//Image
var cellImage = document.createElement("td");
var objImage = document.createElement("img");
objImage.classList.add("obj");
cellImage.setAttribute("align", "center");
cellImage.setAttribute("valign", "bottom");
cellImage.appendChild(objImage);
list.appendChild(cellImage);

//Checkbox
var cellCheckbox = document.createElement("td");
var objCheckbox = document.createElement("input");
objCheckbox.id = id;
objCheckbox.type = 'checkbox';
cellCheckbox.setAttribute("valign", "bottom");
cellCheckbox.appendChild(objCheckbox);
list.appendChild(cellCheckbox);

objImage.src = source;
}

Now, I need to bind a function On Click of each image passing each image id to that function. How can I do this in JScript?

Thanks.

2 Answers 2

1

Well, I'd just (a) attach the id to the image itself and (b) extract this id inside the onclick handler.

Perhaps something a little like this:

Code edit:

var objImage = document.createElement('img');
objImage.setAttribute('myId', id);

Code addition:

function myClickHandler(e)
{
  var clickedImage = this;
  var clickedImageId = this.getAttribute('myId');
  //
  // do something here with the image &/or id
}

I haven't used the .id attribute of the images, since you haven't set them yourself. You have however used the .id attribute of the checkbox. You can't have duplicate IDs on a page, so simply setting the .id of objImage to the same value as the .id of objCheckbox won't make it work.

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

Comments

0

I would say adding this should work:

objImage.addEventListener('click', function() {
   alert(this.id);
}, false);

2 Comments

this prints empty id for each image. Please help to resolve :(
because you are not setting id on the image

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.