0

Have an Ajax request that creates all the elements within a static class.

However, I cannot get the below JQuery to pickup the button/s that are created i.e. cannot fire a test alert message.

I have reviewed a number of posts on this site as regard on click events but I can't get my code to work still.

JQuery and html elements shown below.

JQuery On Click code:

$(".content").on("click",".like",function()

Html (multiple class "post" are created just a single example shown below):

<div class="content"> //Static

  <div class="post">

    <div class="post-text">Some text goes here</div>

      <div class="post-action">

         <input type="button" value="Like" id="like_1_m5s9hr9vfef3ne6ubb533kqhr1" class="like">

         <span id="likes_1_m5s9hr9vfef3ne6ubb533kqhr1">12</span> //id correctly starts with likes not Like

       </div>

    </div>

</div>
CGarden
  • 57
  • 11

2 Answers2

1

Why not use javascript here instead of jQuery?

<input type="button" value="Like" id="like_1_m5s9hr9vfef3ne6ubb533kqhr1" class="like" onclick="youfunctionname('like_1_m5s9hr9vfef3ne6ubb533kqhr1');">

While generating dynamic content, it would be easier for you to write onclick directly before appending the element in html. Also, you can modify the calling of the function in your onclick(For eg.: Pass id, or any other useful data related to do other stuff).

Shakti
  • 496
  • 5
  • 10
1

you just need to use $(this) so you can determine which .like class you have clicked. example below

$(".content").on("click",".like",function(){
    var id = $(this).attr("id"); // get value of id
    alert(id); // alert value
    $(this).css("color","red"); // change color
});
Nyuu
  • 91
  • 1
  • 5
  • That's fantastic and has done the trick. Thank you so much and to everyone that has helped. I really appreciate it. – CGarden Jan 15 '20 at 20:57