gaggina
gaggina

Reputation: 5425

JQUERY how to get id name from dynamic div?

I've got two dynamic generated (from PHP file) divs. This divs are like this:

<div id="x" class="myclass"></div>
<div id="y" class="myclass"></div>

Where X and Y are numbers generated dynamically from a php file. How can I get this id (number) when, for expample, I click on this divs?

I've tried in this way:

$('.myclass').click(function(){

alert(this.attr("id"));

});

But in this way I get only the first id (the first element of myclasses).

How can I fix it?

Upvotes: 1

Views: 15888

Answers (7)

Subash S
Subash S

Reputation: 1

$("#container").on("Events",$(selector),function(e){
    // this will have jquery reference to the container DOM element hence use event.target to capture the element.
    var id=$(e.target).attr("id");
});

JonDoeCA - has given this answer in for a Similar question (I couldn't credit his answer hence referring).

Upvotes: 0

Chad
Chad

Reputation: 19609

try this instead:

$('.myclass').live('click', function() {
   alert(this.id); //or alert($(this).attr('id'))); for the jQuery method
});

Binding events using the $.live() function will bind events to elements that do not yet exists, so when you add new div.myclass elements dynamically they will be bound as well.


Please Note: .live() is now deprecated, use .delegate() or .on() instead.

$(document).on('click', '.myclass', function() {
    alert(this.id);
});

Upvotes: 7

Punit Rathore
Punit Rathore

Reputation: 970

Try this -

$('.myclass').click(function() {
  alert($(this).attr("id"));
 });

Upvotes: 1

Raja
Raja

Reputation: 3618

Do you want to get all the ids which pertains to that class?

try this:

$(".myClass").each(function(){alert($(this).attr("id"));});

You have to invoke the above in another function.

HTH

Upvotes: 0

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36621

$('.myclass').click(function(){
   alert(this.id);
});

take a look at example click on X and Y

http://jsfiddle.net/BJdLJ/4/

Upvotes: 0

Chandu
Chandu

Reputation: 82903

HTML element ID's starting with numbers are not valid.

So try generating an alphanumeric id which starts with a character like "div-10002".

In either case to get the id of the clicked element try this:

$('.myclass').live("click", function(){  
 alert(this.id);  
}); 

or

$('.myclass').live("click", function(){  
 alert($(this).attr("id"));  
}); 

Upvotes: 1

JohnP
JohnP

Reputation: 50019

You need to use the jquery object

$('.myclass').click(function(){
   alert($(this).attr("id"));
});

Also, don't use just a number for an ID. I think only HTML5 allows it now.

Here's a demo : http://jsfiddle.net/SY3m7/

Upvotes: 7

Related Questions