skip to Main Content

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>

2

Answers


  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).

    Login or Signup to reply.
  2. 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
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search