pp182
pp182

Reputation: 107

getting the value of the button clicked in a group of buttons

html

<div id="group1">
  <button>buttonA</button>
  <button>buttonB</button>
</div>

javascript

$('#group1').on('click', function(event) {
  // get ONLY the value of the button cilcked
});

Is something like this possible without attaching an event to every button in the group?

Upvotes: 0

Views: 759

Answers (1)

charlietfl
charlietfl

Reputation: 171669

Add a target selector to the on() and use this or event.currentTarget within the handler function to access the matching element the event occurs on

$('#group1').on('click', 'button', function(event) {
  console.log($(this).text())
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="group1">
  <button>buttonA</button>
  <button>buttonB</button>
</div>

Upvotes: 4

Related Questions