Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On button click, select a sibling element with JQuery

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.

like image 828
user619656 Avatar asked Jan 18 '23 23:01

user619656


1 Answers

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 :)

like image 199
drfranks3 Avatar answered Jan 28 '23 13:01

drfranks3