-1

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?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I dont see postid class. Do you mean reviewid? – Evus Aug 23 '16 at 10:48
  • @Evus hey! Made a mistake. Check it out again. – ProgramAllDay Aug 23 '16 at 10:50
  • I know this is answered, but your jq would have worked if you stepped up one more parent... `var parent = $(this).parent().parent();` The `postcomment` is inside a div (parent1) then that is inside another div - `commentbox` (parent2). -- You were trying to `find()` in the `post_con` div... `closest()` is better anyway :) – Scott Aug 24 '16 at 06:17
  • @Scott thanks for the tip! – ProgramAllDay Aug 24 '16 at 06:21

1 Answers1

3

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);
});
Satpal
  • 132,252
  • 13
  • 159
  • 168