How do you make a click event for an entire class of buttons? jquery

Viewed 80

<div id="tipboard">
                <!--TIPS WILL POPULATE HERE-->
  <li>This is my fully informed tip about the environment and saving puppies<button class="btnLike"           type="button" id="1"></button>
  </li>
  <li>This is a tip!<button class="btnLike" type="button" id="2"></button>
  </li>
</div>

 $(".btnLike").click(function () {
    console.log(this);
    addLike(this);
  });

var addLike = function (likeButton) {
  var idToShow = $(likeButton).attr("id");
  console.log(idToShow);
};

I'm am not getting anything logging to the console. How do I select the current button from a click event using the jquery class selector?

3 Answers

Your code looks right.

The only potential cause could be:

  • jQuery is not available and there's another custom $ defined for something else, thus not showing any error logs about $ not being defined.
  • Your code is run before the DOM is ready.

The first cause is highly unlikely so I suggest you try to run all your code after DOM is ready.

If you're not sure how to do it:

$(document).ready(function () {
  // Add your event handler and all other stuff here...
});

Your snippet isn't working because you haven't imported JQuery. - Run the snippet below to see it work.

 $(".btnLike").click(function () {
    console.log(this);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tipboard">
                <!--TIPS WILL POPULATE HERE-->
  <li>This is my fully informed tip about the environment and saving puppies<button class="btnLike"           type="button" id="1"></button>
  </li>
  <li>This is a tip!<button class="btnLike" type="button" id="2">Click Here</button>
  </li>
</div>

Additionally, if you want to ensure the DOM has loaded before your function runs you can declare the function like this:

$(document).on("click", ".btnLike", function () {
    console.log(this);
  });

I ended up just calling the function from the generated s with onClick.

<li>${tip_message}<button class='btnLike' id=${tip_id} onClick='addLike(this, ${tip_likes})'></button>${tip_likes}</li>`

Related