Question: Im creating the same button in a loop as long as there is a certain condition, and I want to run the same jquery event handler for those buttons.

The problem is that the event handler only works for the first button generated.

My button is generated like this:

```
<?php while($row_c= mysqli_fetch_array($result_comments))
{ ?>
<button name="comment" id="comment" class="button_comment" value="Post">Post</button>
<?php } ?>

```

and the jquery im using is this:

```
$('.button_comment').click(function()
{
    //some staff thats done here
});

```

What should do, so that the event handler works for all buttons that are generated?
Thank you

Answer: 
Your jQuery should work. Note that your buttons form invalid HTML/DOM: The `id` on an element [**must** be unique](http://www.w3.org/TR/html5/dom.html#the-id-attribute). But since you're also using a class (which doesn't have to be unique), and that's what you're using in your jQuery selector, that works: [Live Example](http://jsbin.com/ubiWEvi/1) | [Source](http://jsbin.com/ubiWEvi/1/edit)

Perhaps when you were trying it and it wasn't working, you were using `$("#comment").click(...)`, which would *not* work, because of the `id` issue.
"What should do, so that the event handler works for all buttons that are generated?"
A Fiddle would be a good way to show us the context of your problem `;)`

* Your code is valid because it will attach a handler to every element having 'button\_comment' as a css class

Did you put this code inside a dom ready function ?

```
$(function(){
    /* code here  */
});

```

* You can use [event delegation](http://api.jquery.com/on/#direct-and-delegated-events)
This mean you have to attach the event listener to the first common ancestor of those buttons. This is a good choice when many elements have to trigger the same routine an even more if some of them may be added to the DOM in the futur via AJAX (This keep the page from having to many event handlers attached to it)

Delegation syntax

```
// Event delegation
$( "#Ancestor").on("click", '.button_comment', function() {
    alert( $( this ).val() ); 
});

```