2

I am trying to execute the following Jquery:

$("button.publish").on("click", function(event) {
    alert("hello world");
}); 

On the following HTML:

<button class="publish" data-id="<?= $article['id'] ?>">Publish</button>

But the code doesn't work, the button does not do anything. In the same script file, if I execute a vanilla JS equivalent, with an onClick on the button, it works (below)

function showDetails(article) {
     alert("hello world");
}

I have more Jquery code in the exact same script file that is using the .on() function in the same way and that works fine. Can anyone point me to what is going wrong?

I've also tried the following:

$(document).ready(function() {
  $("button.publish").on("click", function(event) {
      alert("hello world");
  }); 
} 

https://jsfiddle.net/gay0n891/

Mustapha Larhrouch
  • 3,373
  • 3
  • 14
  • 28
Jane
  • 21
  • 3
  • 2
    The only reason your fiddle doesn't work is because you haven't added a reference to jQuery.js: https://jsfiddle.net/8v5tq3fk/. However, if some of the elements in your actual code work then this is unlikely to be the problem. I would assume in this case you're dynamically creating the new HTML element and if so, need to use a delegated event handler. – Rory McCrossan Jun 25 '19 at 10:44
  • Your fiddle is working fine. You just do not include jQuery. – Shahbaz A. Jun 25 '19 at 10:47
  • Sorry, I added the wrong fiddle - edited now. My problem is still present in the code though and other Jquery code works. – Jane Jun 25 '19 at 10:48
  • the problem is most likely the button does not exist at the time when the jquery code is loaded hence not attaching the onclick event to the button – Andam Jun 25 '19 at 10:48
  • In which case it's most likely you need event delegation. See this question: https://stackoverflow.com/q/203198/519413 – Rory McCrossan Jun 25 '19 at 10:50
  • This seemed to fix the issue: $('body').on('click', '.publish', function () { But I will definitely give that a read, thanks :) – Jane Jun 25 '19 at 11:10

0 Answers0