Saff Saff - 6 months ago 15
jQuery Question

Dectect which button and checkbox is clicked

I have,

<div>
<span>Buttons</span>
<div>
<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 />
</div>
<span>Checkboxes</span>
<div>
<input type="checkbox" /> Chbx 1<br />
<input type="checkbox" /> Chbx 2 <br />
<input type="checkbox" /> Chbx 3 <br />
</div>
</div>


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

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 + '#' + this.id);     
});

NOTE: You can attach the event to just the document element and check event.target 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: http://jsfiddle.net/vCjn9/