1

I load data from a PHP page with JQuery and it works fine. Now I want that when I click on one of these loaded elements an alert shows the id of the selected element. How can I do? If I put an element manually into the div "output" it works, but with the element created with $.ajax() it doesn't works. Here is the code.

<input type="text" id="ricerca">
<div id="output" style="border: 1px solid #FF0000;"></div>
$(document).ready(function () {
    // Autocomplete
    $("#ricerca").keyup(function () {
        $(function () {
            var ricerca = $("#ricerca").val();
            $('#output').html("");
            if (ricerca.length > 0) {
                $.ajax({
                    url: 'dati.php',
                    method: 'POST',
                    data: {
                        ricerca: ricerca
                    },
                    dataType: 'json',
                    success: function (data) {
                        for (var i in data) {
                            var row = data[i];
                            var id = row[0];
                            var name = row[1];
                            $('#output').append("<a id='" + id + "' href='#'>" + name + "</a><br>");
                        }
                    }
                });
            }
        });
    });

    // Show ID
    $('#output a').click(function () {
        alert(this.id);
    });
});
Rory McCrossan
  • 306,214
  • 37
  • 269
  • 303
user123456
  • 221
  • 1
  • 3
  • 10

3 Answers3

7

You need to do as follows for dynamically injected html:

$(document).on("click", "#output a", function() {
    alert(this.id);
});

Basically #output wont be there when you first load the page and hence you will need to bind the event to it.

So .on enables you to delegate the event to the handler.

Helpful links:

What is DOM Event delegation?

Direct and delegated events

Community
  • 1
  • 1
Roy M J
  • 6,711
  • 6
  • 43
  • 76
1

You have to use .on() for registering click event of dynamically generated element

// Show ID

    $(document).on("click",'#output a',function() {
         alert(this.id);
    });
Bhushan Kawadkar
  • 27,451
  • 5
  • 33
  • 55
-1

It should be

alert($(this).attr("id"));
Sukanya1991
  • 760
  • 3
  • 16