Gio Gio - 1 year ago 71
Javascript Question

$(this) not "refreshing" with $(document).on('click')

I'm using JavaScript (or jQuery) and I can't retrieve correctly the id of the button calling the event.

Here is a simplified example :
I have 2 buttons with the same class (the class is used for the listener) with id "button_1" and "button_2", I'll click on one of them, launch the event and get the correct id. Now, I'll click on the other button, launch the event and I still get the id of the first button.

Here is the code :

$(document).on('click', '.list-button' , function(e){
var target = || e.srcElement;
var button_id =;

or with jQuery :

$(document).on('click', '.list-button' , function(e){
var button_id = $(this).attr('id');

Both output only the first event caller. The second time, it'll launch the function but it's like " $(this) " is still the first event caller.

EDIT : I simplified too much my example, the alert is working fine and it was crashing later in the code. It was linked to wordpress and I had to undefine the variable to correct it. Thanks for your help even if my request was exceptionnaly useless, I guess you helped me to step back and reading step by step.

Answer Source

Your code works perfectly fine.

$(document).on('click', '.list-button', function(e) {
  var button_id = $(this).attr('id');
<script src=""></script>
<button class="list-button" id="button1">Button 1</button>
<button class="list-button" id="button2">Button 2</button>

Make sure you check your HTML to have it right.

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