0

So have some divs on my webpage that I'd like to have some functionality with once clicked, but these divs aren't hard coded into the HTML, they are rendered using javascript as their appearance depends on what is in a database on the backend.

I set a function on click of these divs but absolutely nothing happens. I can't hard code these into the HTML as I need their appearance to be dependent on the database contents.

Here is my code to render the divs:

$.ajax({
    method: "GET",
    url: "../server-scripts/getTickets.php",
    success: function(result) {
        var safe = JSON.parse(result);
        var tickets = safe["tickets"]
        for(i = 0; i < tickets.length; i++) {
            var stage = tickets[i]["stage"];
            var name = tickets[i]["name"];
            var field = "#"+stage;
            $(field).append("<div class='deployed-ticket'>"+name+"</div>");
        }
    }
});

And here is the code which is supposed to happen when you click on one of the divs:

$(".deployed-ticket").click(function() {
    alert("Select a column to move the ticket");
});

I look at the developer console in my browser and absolutely nothing, the backend works just fine (tested) and this code for other, hard-coded elements works just fine.

Do I need to use different code in order to manipulate div elements rendered through javascript?

Thanks a lot! Much appreciated

DevB
  • 31
  • 1
  • 3
  • You need to use a delegated event handler on dynamic elements. See the question I marked as duplicate for more information – Rory McCrossan Aug 31 '16 at 12:26
  • $(".deployed-ticket").on('click',function() { alert("Select a column to move the ticket"); }); This can help you – Kashyap Aug 31 '16 at 12:27
  • @Kashyap just because you used `on()` does not delegate the event handler. That will make no difference to the OPs problem. – Rory McCrossan Aug 31 '16 at 12:30
  • @RoryMcCrossan - As of jQuery 3.0, .delegate() has been deprecated. It was superseded by the .on() method since jQuery 1.7, so its use was already discouraged. http://api.jquery.com/delegate/ – Kashyap Aug 31 '16 at 12:32
  • I never said to use `delegate()`. Using the delegated form of `on()` is correct, but that's not what you did. I think you need to read the question I marked as duplicate to understand how this works too. – Rory McCrossan Aug 31 '16 at 12:33

0 Answers0