faalbane
faalbane

Reputation: 105

img onclick not working

JS:

htmlStr += '<table id="summary-table">'
         + '<col width="200"><col width="315"><col width="600"><col width="1000">'
         + '<tr><th>Month'
         + '&nbsp;&nbsp;&nbsp;<img id="azsort-month" src="sort.png" alt="Sort by Alphabetical Order (A to Z)" style="width:20px; height:20px;">'
         + '</th><th>Header2</th><th>Header3/th><th>Header4</th></tr>';

I've tried both

htmlStr += '<table id="summary-table">'
         + '<col width="200"><col width="315"><col width="600"><col width="1000">'
         + '<tr><th>Month'
         + '&nbsp;&nbsp;&nbsp;<img id="azsort-month" src="sort.png" onclick="alert("test")" alt="Sort by Alphabetical Order (A to Z)" style="width:20px; height:20px;">'
         + '</th><th>Header2</th><th>Header3/th><th>Header4</th></tr>';

and

$(document).ready(function() {
        $('#azsort-month').click(function(){
            alert("test");
        });
    });

and

$('#azsort-month').click(function(){
  alert("test");
});

the htmlStr var is part of a function that displays a JSON output as an HTML table; it works for whole table except the click event on this img

Upvotes: 2

Views: 1049

Answers (1)

The Process
The Process

Reputation: 5953

You have to use event delegation, as #azsort-month img doesn't exist at the time you're attaching that event handler, so:

$(document).on('click','#azsort-month',function(){
  alert("test");
});

Upvotes: 3

Related Questions