Johnny Appal Johnny Appal - 1 month ago 5x
MySQL Question

jQuery - click() not working when attached to anchor created in PHP

I have this PHP code which outputs HTML anchor elements on a page:

echo '<a id="message-button" class="button">Message</a>';
echo '<a id="add-img-button" class="button">Add Image';
else if(!$isFollowing)
echo '<a id="follow-button" class="button">Follow';
echo '<a id="follow-button" class="button">Unfollow';
echo "</a>";

When I load the web page, I get this, as expected:

<a id="message-button" class="button">Message</a><a id="follow-button" class="button">Unfollow</a>

But when I try to attach a click() function to it, the clicking doesn't work. This is the jQuery code. (It's weird because all of my other JS on the page works flawlessly."

$('.button').click(function() { alert("HEY"); }); // It doesn't work grabbing by #follow-button or #message-button either.

What did I do wrong here? I've spent an hour looking at these snippets of code to no avail.


Try this:

$('.button').live('click',function() { alert("HEY"); });

Put it in your $(document).ready function.