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>

5 Answers 5

46
$("input").click(function(e){
    var idClicked = e.target.id;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Event.target will only work in this specific case (<input> 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 for proper handling of delegated events
6
$(function() {
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});

Comments

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/

Comments

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

3 Comments

Technically, e represent the click event object, not the button object.
@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 Well, clearly I've just been out-technicallyed. Thanks for the details
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.