0

Why this work

$("#tag-search").autocomplete({
        autoFocus: true,
        source: tags,
        messages: {
            noResult: '',
            results: function () {}
        },
        select: function (e, ui) {
            $('.tags').append('<span class="tag-style">' + ui.item.value + '<i class="fa fa-times tag-del" aria-hidden="true"></i></span>');
            ui.item.value = "";
            $('.tag-del').click(function () {
                $(this).parent().remove();
            });
        }
    });

and this no?

$("#tag-search").autocomplete({
        autoFocus: true,
        source: tags,
        messages: {
            noResult: '',
            results: function () {}
        },
        select: function (e, ui) {
            $('.tags').append('<span class="tag-style">' + ui.item.value + '<i class="fa fa-times tag-del" aria-hidden="true"></i></span>');
            ui.item.value = "";
        }
    });

    $('.tag-del').click(function () {
        $(this).parent().remove();
    });

I have never understood how javascript is compiled and how work functions! Someone can help me? And last thing: is better write javascript in body page or in a external file? If i should write in external file how can send php response to javascript file? Thanks!

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
KILLERIX
  • 33
  • 1
  • 6
  • It's not about compiling is about synchrony `autocomplete` is asynchronous (gets executed in the background while the rest of script keeps running), so your `click` event can't be added to `.tag-del` element since it doesn't exist until `select: function` is called in your autocomplete function. – Lixus Oct 12 '17 at 16:13
  • The problem is because, in the second example, `.tag-del` does not exist in the DOM when you attempt to bind an event handler to it. You can instead bind the handler at the point you create the element - which is what your first example is doing - or better yet, you can use a single delegated event handler on a parent element. See the duplicate I marked for how to do that – Rory McCrossan Oct 12 '17 at 16:20

0 Answers0