abhishek vashistha
abhishek vashistha

Reputation: 91

How to add onclick event on image dynamically

I am creating images with onclick properties dynamically using jQuery

 function create() {
     divElem    = $("<div class='row'>");
     $('#bankList').append(divElem);
     elem = $("<div class='col-sm-3', style='height:110px'>");
     image = $("<img style=' max-width:90%'>");
     var imageFile = '${pageContext.request.contextPath}/images/' + prop[j];
     image.attr('src', imageFile);
     image.attr('id',prop[j]);
     image.on("click",submitForm(this.id));
     elem.append(image);
     divElem.prepend(elem);
 }

Function create is called on winodw.onload and submit form gets called onload only. It should be called on clicking of image

Upvotes: 0

Views: 2064

Answers (2)

bitto kazi
bitto kazi

Reputation: 171

you can add img onClick function on document

$(document).on('click', 'img', function() {
    alert('Click on Image id: '+$(this).attr('id'));
});

Upvotes: 1

Oleg Pnk
Oleg Pnk

Reputation: 332

Your event handler is wrong. You could provide an anonymous handler function instead:

image.on("click",function() {
  submitForm(this.id);
});

See details in .on method documentation.

Upvotes: 2

Related Questions