0

I have a previous question re loading html via ajax:

javascript - load html content from ajax call

but I face small issue with attaching a click listener:

<html th:remove="tag" xmlns:th="http://www.thymeleaf.org" xmlns:ber="http://berwickinsurance.com/thymeleaf"
    xmlns:eph="http://ephibian.com/thymeleaf" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<div>
<div id="note-list-container2">
 ....
</div>
<div id="file-list-container2">

    <table style="width: 100%; height: 100%" class="table">
        <thead>
        <tr>
            <th></th>
            <th>Name</th>
            <th>Category</th>
            <th>Created On</th>
            <th>Size</th>
            <th></th>
        </tr>
        </thead>
        <tbody>
        <th:block th:each="note : ${model.notes}" th:object="${note}">
            <tr th:each="file : *{files.data}" th:object="${file}">
                <td><i
                        th:replace="~{layout/custom-frag::file-ico(*{mimeType})}"></i></td>
                <td><a target="file"
                       th:href="@{*{#uris.escapePath('/files/'+id+'/'+name)}}"><strong
                        th:text="*{name}">contractUHCSigned.pdf</strong></a></td>
                <td><span class="badge" th:text="${note.category.name}">Category</span>
                </td>
                <td> <span th:text="*{#joda.defaultDateTime(createDate)}">Create On</span></td>
                <td><th:block
                        th:text="*{#prettyTime.humanReadableByteCount(size, true)}">400 kb</th:block>
                </td>
                <td><a target="file"
                       th:href="@{*{#uris.escapePath('/files/'+id+'/'+name)}}">View</a></td>
                <td ><a id="noteFileDeletion"  onClick="handleFiledeletion()"  title="Remove File" class="delete-btn text-danger"  data-confirm="delete file"><i class="fa fa-remove"></i></a></td>
            </tr>
        </th:block>
        </tbody>
    </table>
</div>
</div>
   <script>
function handleFiledeletion(){
.....
}
</script>
</html>

It's not triggering the handleFiledeletion method.

I tried another approach:

$("#noteFileDeletion").on('click', function() {
        var deleteBtn = $(this);
        var url = $(this).data('url');
        url = url +"?csrf_token="+App.config.csrfToken;
        var msg = "Are you sure you want to "+$(this).data('confirm')+"?";
        bootbox.confirm(msg, function(result){
            if(result){
                $.ajax({
                    processData : false,
                    "type" : "DELETE",
                    "url" : url,

                })
                    .success(function( data ) {
                        window.location.href='/applicationProducts';
                    });
            }
        });
    });

but it's not triggering the event handler either.

What I missing?

cssyphus
  • 37,875
  • 18
  • 96
  • 111
Mina Fawzy
  • 20,852
  • 17
  • 133
  • 156
  • `th:block`? `th:each`? It looks like there's more than just HTML and JavaScript at play here. What is the actual resulting HTML? If you have more than one of these rows and are re-using that `id` value then the HTML you have is invalid. – David Sep 10 '20 at 13:33
  • these tags for thymeleaf – Mina Fawzy Sep 10 '20 at 13:35

1 Answers1

1

When using .on(), you must be sure that you attach the .on() listener to an element that is already in the DOM at initial page load.

Try this - if it works, then you can try moving the listener further down the tree:

$(document).on('click', function(){
   var deleteBtn = $(this).find('#noteFileDeletion');
   etc.

Update:

I've updated the above code with the missing bit - many thanks to @David for catching the omission.

$(document).on('click', '#noteFileDeletion', function(){
    alert('You clicked ID noteFileDeletion');
});
cssyphus
  • 37,875
  • 18
  • 96
  • 111
  • I have done this on the html itself with script tag I tried both function and attach click listner with .oin – Mina Fawzy Sep 10 '20 at 13:37
  • 2
    `$("#noteFileDeletion").on('click', function() {` is wrong ***IF*** the element with `id=noteFileDeletion` is part of the HTML injected via ajax. It is only correct if that element already exists in the DOM at initial page rendering. Best way to test it is to try using `$(document).on()` as your click handler and see if that works with a console log... – cssyphus Sep 10 '20 at 13:39
  • Thanks but thats partially working I mean when I click anywhere on page its fired, how I can determine if this a tag clicked? – Mina Fawzy Sep 10 '20 at 13:55
  • I don't know if [this](https://stackoverflow.com/a/10707556/1447509) will help but you can have a try. Another idea is to inject additional javascript along with the HTML (js must be between `` tags - and don't forget to wrap the js code in `$(function(){ //code here });` ) and you can set click handlers in there. The reason you had to use `.on()` is because the intial js click handlers are set up on page load. If you inject additional js with your injected HTML, those click handlers are attached at the time of injection and can be more specific. – cssyphus Sep 10 '20 at 14:06
  • @MinaFawzy: An optional second string argument to `.on()` filters the target element. For example: `$(document).on('click', '#noteFileDeletion', function () { /.../ });` – David Sep 10 '20 at 14:09
  • @David - Ah, right, I forgot about that - good catch! – cssyphus Sep 10 '20 at 14:09
  • Thanks, guys you really save my day, appreciated – Mina Fawzy Sep 10 '20 at 14:53