jQuery click function only works on first element
In HTML, id
refers to a unique identifier. In other words, it is against standards to have 2 elements with the same id
. jQuery here behaves correctly.
Use a class
instead of an id
to identify your tags as such:
HTML:
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a class="edit" href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a class="edit" href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
JavaScript:
$(document).ready(function() {
$('a.edit').click(function(){
alert($(this).parent("li").attr("id"));
})
});
Alternatively, since the parent tag already seems to have a unique class, you could simply use it to target wanted tags. This would reduce what I call "class noise" (the defining of useless class to target element which could be targeted by their parent's unique attributes).
HTML:
<ul id="sortable" class="ui-sortable">
<li class="sortable" id="listItem_1">
<a href="#">edit</a>
<span id="title">List item 1</span>
</li>
<li class="sortable" id="listItem_2">
<a href="#">edit</a>
<span id="title">List item 2</span>
</li>
etc..
</ul>
JavaScript:
$(document).ready(function() {
$("li.sortable a:contains('edit')").click(function(){
alert($(this).parent("li").attr("id"));
})
});
I think this is because use use the same id for each element. Try using a class instead.
<a href="#" class="edit">edit</a>
And then
$('a.edit').click(...)