zeeshan
zeeshan

Reputation: 51

cannot retrieve the id of dynamically created div

I have created a dynamic div, along with the table...I want that when i click the image inside the div, it will give the the id of the div on which i have clicked...below is the code. Please any one point out where the mistake is...!? In the alert box i am unable to get the id of the div

following code creates the div

function create_newGrid() {
    //create div for corresponding table
    var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab" + nooftables });
    var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", "onclick": "openTableSettings(this);" })
    $(tableDiv).append(divImage);
    // append grid to designer
    $(document.getElementById("center")).append(tableDiv);
    $(document.getElementById("center")).append(table);
}

following is the function that executes when a image in the div is clicked

function openTableSettings(div) {
    alert($(div).attr("id"));

}

Upvotes: 3

Views: 423

Answers (4)

gilly3
gilly3

Reputation: 91497

You are passing a reference to the img to openTableSettings(). Use .closest() to get the div:

function openTableSettings(img) { 
    alert($(img).closest("div").attr("id")); 
} 

Upvotes: 1

Ram
Ram

Reputation: 144689

try this:

$("div > img").click(function() { 
    id = $(this).parent("div").attr("id");
    alert(id);    
})

Upvotes: 0

Andrew Barrett
Andrew Barrett

Reputation: 19901

The problem is that you have the onclick on the image, which doesn't have an ID. If you run this in your browser console, it will add a div with text to the bottom of this page and you can see the id being retrieved properly. (your code but adapted)

//create div for corresponding table
var tableDiv = $('<div/>').attr({ "id": "settingsDiv-tab", "onclick": "alert($(this).attr('id'));"});
var divImage = $('<p>this is a big bunch of text</p>');
tableDiv.append(divImage);
$(document.body).append(tableDiv);

Upvotes: 1

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

Maybe it's better if you do

var divImage = $('<img/>').attr({ "src": "settingsImage/settings.png", class: "clickable"});

and then

$(window).on('click', 'img.clickable', function(){
   alert(this.id);
});

(this assumes jQuery >= 1.7)

Upvotes: 0

Related Questions