tags:

views:

91

answers:

4

hi

html is

<table>
<tr>
<td><img src="ex.jpg"  class="edit" name="n1"></td>
<td><img src="ex.jpg"  class="edit" name="n2"></td>
<td><img src="ex.jpg" class="edit" name="n3"></td>
<td><img src="ex.jpg"  class="edit" name="n4"></td>
</tr>
</table>

Jquery code is:

$(".edit").click(function() {

$(".edit").each(function(){

alert($(this).attr("name"));

});

});

Here is, it only alerts one name, i mean just alerts "n1".

How can i alert name attr. of each element ?

Thank you

+2  A: 

You can't have multiple elements with the same ID (hence the name: ID). If you do, #image always matches only the first element with the given ID (in your case the #n1 image). You can, however, add multiple classes to an element:

HTML:

<img class="edit image" name="foobar" />

JS:

$(".image").each(function(){
    alert($(this).attr('name'));
});

this in this context is the plain DOM element. You first have to change it into an jQuery object (var $that = $(this)) before you can use .attr() on it.

Boldewyn
It might even be better to do just `$('img.edit').each(..);`
Ikke
Perhaps, but in any case the `id` attributes should be changed to `image-1`, `image-2`, etc. or removed.
Blixt
i deleted id, and tried as you said but it alerts undefined now for a reason
Ahmet vardar
i fixed it, i dont need each function to do it, removed it and it works great
Ahmet vardar
A: 

var title = $("img").attr("name"); alert (title);

Treby
A: 

Your HTML is actually invalid; no two elements are allowed to have the same id.

Amber
A: 

I think your problem is that id of element should be unique so jQuery may not try to get all of them (so you only have one element).

My suggestion is to change the id of each.

In case you can't do that for want ever reason, try this:

$("img[id='image']").each(function(){

alert(this.name);
// Or alert($(this).attr("name"));

});

I didn't test it so sorry if there is some mistake.

Hope this helps.

NawaMan