skip to Main Content

Using the answers posted from here, I created a button group. However when I press the button, the text shown in the alert box returns all the buttons that are pressed, how can I make it so that only the button pressed gets returned?

$(".btn-group> .btn").on("click", function() {
  console.log($('.btn-group> .btn').text());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<div class="btn-group" data-toggle="buttons-radio">
  <button class="btn">1</button>
  <button class="btn">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
</div>

2

Answers


  1. This selector returns all of the matching elements:

    $('.btn-group> .btn')
    

    So reasonably this would either return all of the text, or potentially default to the first matching text (it’s the latter):

    $('.btn-group> .btn').text()
    

    You don’t need to re-select the elements in the first place though. If you just want the element which was clicked, this refers to that in jQuery’s event handlers:

    $(".btn-group> .btn").on("click", function(){
        alert($(this).text()); 
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="btn-group" data-toggle="buttons-radio">
      <button class="btn">1</button>
      <button class="btn">2</button>
      <button class="btn">3</button>
      <button class="btn">4</button>
    </div>
    Login or Signup to reply.
  2. This should work for you

    $(".btn-group > .btn").on("click", function(){
        alert($(this).text()); 
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search