Reputation: 1041
I'm trying to get the id attr from different onclicks.
Here is the html I have.
<div id="name-1">
<a href="#" class="view">
<div>
<div id="name-2">
<a href="#" class="view">
<div>
<p>Name: <span class='name'></span></p>
<script>
$(".view").click(function() {
var id = $(".view").closest("div").attr("id");
$('.name').html(id);
});
</script>
When I click the first view I see "name-1" however when I click the second view nothing happens. Also, when I click the second name it shows "name-1". I know this is probably easy to solve but it's friday so I appreciate the help.
Upvotes: 0
Views: 1303
Reputation: 4004
The reason is you are using the view
class selector to get the closest id. So, it looks for the first available view
and gets you the id for first DIV
.
Consider using $(this)
to get the closest id for the clicked element.
$(".view").click(function() {
var id = $(this).closest("div").attr("id");
});
Don't forget to read this article on "jQuery this": http://remysharp.com/2007/04/12/jquerys-this-demystified/
Upvotes: 1
Reputation: 4748
Change
var id = $(".view").closest("div").attr("id");
to
var id = $(this).closest("div").attr("id");
Right now your current code is looking at the first .view
on the page rather than the .view
whose click event was triggered.
Upvotes: 4