Saff Saff - 1 year ago 89
jQuery Question

Dectect which button and checkbox is clicked

I have,

<button id ="button_1" class="button">Btn 1</button><br />
<button id ="button_1" class="button">Btn 2</button><br />
<button id ="button_3" class="button">Btn 3</button><br />
<button id ="button_4" class="button">Btn 4</button><br />
<input type="checkbox" /> Chbx 1<br />
<input type="checkbox" /> Chbx 2 <br />
<input type="checkbox" /> Chbx 3 <br />

How do i determine which button/checkbox has been clicked? I could attach a click event to each button but i'm looking for any method/tricks you guys might have that's a bit more effiicient.

Answer Source

You can attach a click to ALL buttons and inputs and check the tagName, ID etc..

$(document).on('click', 'input, button', function(event) {
    alert(this.tagName + '#' +;     

NOTE: You can attach the event to just the document element and check to achieve the same, but the above is more efficient as the callback will be fired only for inputs and buttons instead of for all elements.

See Demo:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download