21

How to detect which dynamic button is clicked?
Note: The #dCalc Element is added dynamically...

<!-- STATIC -->
<div id="dBlock">

  <!-- ADDED DYNAMICALLY -->
  <div id="dCalc">
    <input id="firstNumber" type="text" maxlength="3" />
    <input id="secondNumber" type="text" maxlength="3" />
    <input id="btn1" type="button" value="Add" />
    <input id="btn2" type="button" value="Subtract" />
    <input id="btn3" type="button" value="Multiply" />
    <input id="btn4" type="button" value="Divide" />
  </div>

</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
eagle
  • 567
  • 1
  • 6
  • 24

5 Answers5

46
$("input").click(function(e){
    var idClicked = e.target.id;
});
genesis
  • 50,477
  • 20
  • 96
  • 125
  • `Event.target` will only work in this specific case (`` with no children) - Always use `Event.currentTarget` instead of `Event.target` - no matter what (or unless you really know what you're doing). See [this answer](https://stackoverflow.com/a/75204988/383904) for proper handling of **delegated events** – Roko C. Buljan Jan 23 '23 at 01:09
6
$(function() {
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
RoccoC5
  • 4,185
  • 16
  • 20
1

Since the block is added dynamically you could try:

jQuery( document).delegate( "#dCalc input[type='button']", "click",
    function(e){
    var inputId = this.id;
    console.log( inputId );
    }
);

demo http://jsfiddle.net/yDNWc/

Esailija
  • 138,174
  • 23
  • 272
  • 326
1

jQuery can be bound to an individual input/button, or to all of the buttons in your form. Once a button is clicked, it will return the object of that button clicked. From there you can check attributes such as value...

$('#dCalc input[type="button"]').click(function(e) {
    // 'this' Returns the button clicked:
    // <input id="btn1" type="button" value="Add">
    // You can bling this to get the jQuery object of the button clicked
    // e.g.: $(this).attr('id'); to get the ID: #btn1
    console.log(this);

    // Returns the click event object of the button clicked.
    console.log(e);
});
Highway of Life
  • 22,803
  • 16
  • 52
  • 80
  • 1
    Technically, `e` represent the click event object, not the button object. – Blazemonger Oct 27 '11 at 16:52
  • @mblase75, actually the click event object is `e.originalEvent`, `e` is jQuery generated custom object that has "cross browserized" properties for convenience, and doesn't include some things that are in the `e.originalEvent` :P – Esailija Oct 27 '11 at 16:57
  • @Esailija Well, clearly I've just been out-technicallyed. Thanks for the details – Blazemonger Oct 27 '11 at 17:01
0

Detect event on dynamically created elements

Two examples, jQuery and vanilla JavaScript ahead:

jQuery

Use the .on() method with delegated events, which follows this syntax:

$("staticParentSelector").on("eventName", "dynamicChildSelector", handlerFn);

Example:

// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future

$("#dBlock").on("click", '[type="button"]', (evt) => {
  
  const staticParent = evt.delegateTarget; // This is #dBlock
  const dynamicChild = evt.currentTarget;  // This is the dynamic child
  
  console.log(`Static Parent ID is: ${staticParent.id}`)
  console.log(`Dynamic child ID is: ${dynamicChild.id}`)
  
});
<!-- STATIC -->
<div id="dBlock">

  <!-- ADDED DYNAMICALLY -->
  <div id="dCalc">
    <button type="button" id="btn1">Add</button>
    <button type="button" id="btn2">Subtract</button>
    <button type="button" id="btn3">Multiply</button>
    <button type="button" id="btn4">Divide</button>
  </div>

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>

JavaScript

The same in vanilla JavaScript can be achieved like the following, with the difference in that JS has no notion of delegateTarget (which is a jQuery property on their proprietary Event object) therefore the slight modification:

// Assign event listeners to dynamic child elements
// Will work for either existent elements or inserted in the future

document.querySelector("#dBlock").addEventListener("click", (evt) => {
  
  const staticParent = evt.currentTarget; // This is #dBlock
  const dynamicChild = evt.target.closest('[type="button"]');  // This is the dynamic child
  
  if (!dynamicChild) return; // Do nothing (no designated dynamic child is clicked)
  
  console.log(`Static Parent ID is: ${staticParent.id}`)
  console.log(`Dynamic child ID is: ${dynamicChild.id}`)
  
});
<!-- STATIC -->
<div id="dBlock">

  <!-- ADDED DYNAMICALLY -->
  <div id="dCalc">
    <button type="button" id="btn1">Add</button>
    <button type="button" id="btn2">Subtract</button>
    <button type="button" id="btn3">Multiply</button>
    <button type="button" id="btn4">Divide</button>
  </div>

</div>

as you can see neither of the above implementations stick solely on the Event.target Element per-se, for the reason that if we had i.e. an icon inside the buttons (like: <button id="add" type="button">Add <i class="icon-plus"></i></button>) and if a click landed on the icon directly, the Event.target would end up being the icon, not the Button Element - and we might miss to retrieve the needed data, like the specific button ID etc, resulting in a broken app logic.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313