eagle
eagle

Reputation: 835

Detect event (like click) on dynamic content

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>

Upvotes: 21

Views: 69432

Answers (5)

Roko C. Buljan
Roko C. Buljan

Reputation: 206078

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.

Upvotes: 0

Highway of Life
Highway of Life

Reputation: 24331

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);
});

Upvotes: 1

Esailija
Esailija

Reputation: 140220

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/

Upvotes: 1

RoccoC5
RoccoC5

Reputation: 4213

$(function() {
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});

Upvotes: 6

genesis
genesis

Reputation: 50976

$("input").click(function(e){
    var idClicked = e.target.id;
});

Upvotes: 46

Related Questions