4

I have this code:

<div class="item">
  <div class="hidden">44</div>
  <input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
  <script type="text/javascript">
    $(document).ready(function () {
        $('#btnAddCommentForAnswer').click(function () {
            alert(XXX);
        });

    });
  </script>    
</div>

<div class="item">
  <div class="hidden">12</div>
  <input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
  <script type="text/javascript">
    $(document).ready(function () {
        $('#btnAddCommentForAnswer').click(function () {
            alert(XXX)
        });

    });
  </script>  
</div>

what code should I put at XXX to get the content of the div with class=hidden when i press the button at the same div with class=item?
If you click the first button you should get 44, and for clicking the second button you get 12.

4 Answers 4

8

id's are meant to be unique; you may wish to consider changing the id to a class. With that in place, you could use a script like the following to achieve what you want:

$(document).ready(function() {
    $('.btnAddCommentForAnswer').click(function() {
        alert($(this).siblings('.hidden').text());
    });
});

Here's a JSFiddle example: JSFiddle

Also, you don't need to have two script tags in your script! This one script wrapped in <script> tags is all that is necessary :)

Sign up to request clarification or add additional context in comments.

Comments

1

Haven't tried but this should work:

$(this).closest('div').text()

Comments

0

You need not repeat the javascript code multiple times. Also, you cannot use id in jquery as the buttons have same id. Here is the jsfiddle http://jsfiddle.net/t8XJZ/ which might solve your problem.

Comments

0

maybe this is more useful for you...

jquery:

$(document).ready(function () {
     $('.item').each(function(){
         $(this).find("#btnAddCommentForAnswer").click(function () {
            alert($(this).prev(".hidden").text())
        });
    });
 });

html:

<div class="item">
  <div class="hidden">44</div>
  <input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />  
</div>

<div class="item">
  <div class="hidden">12</div>
  <input type="submit" id="btnAddCommentForAnswer" value="Add Comment" />
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.