19

how to detect which button is clicked using jQuery

<div id="dBlock">
 <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>

Note: above "dCalc" block is added dynamically...

eagle
  • 506
  • 1
  • 6
  • 22

4 Answers4

43
$("input").click(function(e){
    var idClicked = e.target.id;
});
genesis
  • 49,367
  • 20
  • 94
  • 122
5
$(function() {
    $('input[type="button"]').click(function() { alert('You clicked button with ID:' + this.id); });
});
RoccoC5
  • 4,165
  • 15
  • 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
  • 134,577
  • 23
  • 263
  • 318
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
  • 20,819
  • 15
  • 46
  • 76
  • 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