Reputation: 1548
OK, I have been trying to obtain the id of a particular link, but attr('id') keeps returning undefined.
Here is the structure of the html:
<hr />
<span>The Huffs</span><br />
<img src="images/thumbnails/websitethumbs/graphicdesign/logos/th_2.jpg" height="120"><br />
<span>the huff family<span><br />
<span>$10.99<span><a id="btn_2" class="btn hidden" href="cart.php?add=2"> add</a><br />
<form method="post">
<select class="sizeSelect" id="size_2">
<option value="0">Select Size</option><option value="7x5">7x5</option><option value="16x12">16x12</option><option value="10x10">10x10</option></select>
<span> + $<span class="shipping" id="shipping_2"></span> shipping</span>
</form>
<hr />
And I want to traverse from #size_2 to the a tag with the id #btn_2, and I need to grab that ID and save it to a variable.
I have been using the following jquery code:
$('.sizeSelect').change(function(size) {
sizeId = $(this).attr('id');
addBtn = $(sizeId).parent().closest('.btn').attr('id');
...
so I want add btn to return "btn_2" but it only return "undefined." I have tried prev() instead of closest also... well I have tried lots of stuff. Hours into this and I would really appreciate some insight :)
Thanks in advance!
Upvotes: 0
Views: 290
Reputation: 78
You have to change your code a little bit from
addBtn = $(sizeId).parent().closest('.btn').attr('id');
to
addBtn = $('#'+sizeId).parent().siblings('.btn').attr('id');
Upvotes: 0
Reputation: 56497
Look at this code:
sizeId = $(this).attr('id');
addBtn = $(sizeId).parent().closest('.btn').attr('id');
In your case the ID of .sizeSelect
is size_2
, so
sizeId == 'size_2';
so what you are doing is actually
addBtn = $('size_2')
and it should be
addBtn = $('#size_2')
Upvotes: 0
Reputation: 100195
Do you mean something like:
$('.sizeSelect').change(function() {
var sizeId = $(this).attr("id").split("_")[1]; // gets 2 from size_2
//since id's are unique
var addBtn = "btn_"+sizeId; //anchor id
});
Upvotes: 1