Using parent() to get values in jQuery

61 views Asked by At

I'm printing the below HTML piece in a loop.

<div class = "commentbox">
    <input type="hidden" name="postid" value="${p.postid}" /> 
    <input type="hidden" name="username"  value="${username}" /> 
        <input type="hidden" name="source" value="user_home" />
    <textarea name="comment" cols="40" rows="1" class="add_comment"
        placeholder="Add a comment..."></textarea>
    <div class="post_con">
        <button type="submit" class="postcomment">Post</button>
    </div>
</div>

I have this jQuery piece where I would like to get the <input name="postid"> value when clicking on the <button class="postcomment">.

$(".postcomment").click(function(){
    var parent = $(this).parent();
    var postid = parent.find(".postid").val();
    console.log(postid);
});

However, it logs undefined. How can I get the postid value?

1

There are 1 answers

1
Satpal On

You can use .closest() to traverse up to commentbox element which is common parent of both element postcomment and postid elements.

Then as you have specified postid in name attribute you can use Attribute value selector.

$(".postcomment").click(function() {
    var parent = $(this).closest('.commentbox');
    var postid = parent.find("[name=postid]").val();
    console.log(postid);
});