2

I'm trying to add a click event to the delete button in my index.handlebars file. However, the button doesn't register a click even though I'm targeting the button in my javascript file. Here's the handlebars code below:

        <ul class="collection with-header">
            {{#each Jokes}}
            <li class="collection-item">
                <div>Jokes: {{joke}} {{username}}
                    <button type="submit" data-id="{{id}}" class="waves-effect waves-light btn userdelete" method="delete">delete the joke</button>
                </div>
            </li>
            {{/each}}
            <h4></h4>
        </ul>

Here's the click event in the javascript file:

        $(".userdelete").on("click", function () {
            const idToDelete = $(this).data("id");
            console.log("click");
            $.ajax({
                url: `/api/Jokes/${idToDelete}`,
                method: "DELETE"
            }).then(function () {
                location.reload();
            });
        });

What am I doing wrong? The console.log "click" doesn't even appear in the browser console. Any help is much appreciated.

1 Answers1

0

It is due to the .userdelete element being generated dynamically - the element doesn't exist yet, so you can't bind anything to it. Try binding it to a parent element like this:

$(".collection").on("click", ".userdelete", function() { /* ... */ });

For more information, take a look at this post

muhmann
  • 191
  • 9