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
This selector returns all of the matching elements:
So reasonably this would either return all of the text, or potentially default to the first matching text (it’s the latter):
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:This should work for you