raised click event on dynamic html img

raised click event on dynamic html img


Hi All,

The user is able to construct a table by clicking in a button,  Here is the table:

  1. <table id="MyTable">
  2.                 <tr style="vertical-align:top" >
  3.                     <td>IN</td>
  4.                     <td>OUT</td>
  5.                     <td></td>
  6.                 </tr>
  7. </table>


So the user presses the IN button and the timenow is entered in the IN column, if it presses the out, the timenow is entered in the out column, and at the same time i add a delete image on the third column

  1. var cell3 = row.insertCell(2);
  2. cell3.innerHTML = "<img class=\"imgDelete\" style=\"cursor: pointer;\" alt=\"" + rowCount + "\" src=\"" + redCrossImage + "\"/>";

What i am trying to achieve now is that when the user clicks on a row delete image, to be able to delete that row, for that i have added the row count in the alt image property thus i know which row to delete.So my first attempt was to add it like $(".imgDelete").click(function () ... After reading the  .on documentation i understand that this  cannot work as the html element is not in the document. I have tried to used a delegate on the document.ready something on the lines of 

    
$("#MyTable tr").on("click", function(event){
alert($(this).text());
});



but it is not working...So i have tried to attache the event handler after creating the td html


  1.                     var inOutImageDelete = $(cell3);
  2.                     //Your .click() handlers only work with elements that are in the page at document.ready time. The elements you add dynamically were not present then so they have no click handlers.
  3.                     $(inOutImageDelete).on("click", function () {
  4.                         alert("image click");
  5.                         var src = $(this).attr("src");
  6.                         alert(src);
  7.                         var alt = $(this).attr("alt");
  8.                         alert(alt);
  9.                     });


and my problem is that src and alt are both undefined!...Could some one please let me know how can i fix this? Found solution :
The image is a child of "this" thus i should be using:  var row = $("img", this).attr('alt');

However, using the rowIndex on the alt attribute is not the right solutions, as if i have 3 rows, and delete row 2, and then try to delete row 3 , the row index has changed!, so when clicking on that image, can i get the entire row and delete it with some jquery?