erol_smsr erol_smsr - 1 year ago 127
jQuery Question

jQuery .attr returns undefined

I have this HTML with the element .replyLink and an input field with type hidden that has a value (in this case 462). I want to be able to get the value of the value attribute of the input .hddnScrapId when I click on the .replyLink element. This is the HTML:

<div class="scrapItemParent">
<input class="hddnScrapId" type="hidden" value="462"/>
<img class="scrapProfilePic" src=" static/img/user/personalProfilePicture/mod_50_50/150972db1a0c9e863746c12797398b6e40ae05c8.jpg" />
<div class="scrapContent"><br />
<video class="scrapVideo" controls>
<source src="../../../scrapll_m/static/vid/4045e7944d8ea8f10dd4826a1e1595a7cef73b0c.mp4" type="video/mp4">
</video><br />
<span class="scrapTime">2014-05-27 16:51:22<br />Erol Simsir
<a class="replyLink" href="javascript:void(0);">Reply</a>
<a class="replyClose" href="javascript:void(0);">x</a>

This is the JS I have now:

var hddnScrapId = $(this).closest(".hddnScrapId").attr("value");

This keeps saying 'undefined'. I guess the problem occurs because the closest() function can't find the input field hddnScrapId. Why doesn't it work?

Answer Source

1) closest only looks among the element itself and its ancestors and the .hddnScrapId element isn't a parent of the clicked element.

2) To get the uptodate value, you must use val, not attr("value").

You want this :

var hddnScrapId = $(this).closest(".scrapItemParent").find(".hddnScrapId").val();