2

I am doing a project and i use ajax to load content into page.

my jquery function is :

function load_room() {
    var sem = 0;

    $.ajax({
        url: 'ajax/room_ajax.php?option=2',
        type: 'POST',
        data: { 'sem': sem },
        dataType: "json",
        success: function (data) {
            console.log(data[0]);
            $("#room").html("");
            for (var i = 0; i < data.length; i++) {
                var x = i + 1;
                $("#room").append("<tr><td>" + x + "</td><td>" + data[i]['room_name'] + "<td><a id='edit' href='#'>edit</a></td></tr>");
            };
        }
    });
}

The content load success fully but when i click on the <a id='edit' href='#'>edit</a> element it does not trigger the corresponding click event. The code is like:

$('#edit').on('click', function(){
    alert("hai")
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55

2 Answers2

5

You are binding event to element those are present in DOM the time on() is executed. Delegate event to static parent for elements added dynamically.

$('#room').on('click', "#edit", function(){
     alert("hai")
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Rayon
  • 36,219
  • 4
  • 49
  • 76
Adil
  • 146,340
  • 25
  • 209
  • 204
0

just note you are clearing the html from #room but then appending trs' and td's

         $("#room").html("");

            $("#room").append("<tr><td>...

If #room is the div that houses a table, this will cause an issue since you have cleared the table and th structure from the div. Unless #room is the id of the table and you are simply clearing all trs etc from it - but since you did not post the html - I cannae say.

also all of your rows will have an <a> with the id of "edit" because you are not differentiating them with each append. Meaning you wikl have multiple ids of "edit" when the table is created with this function.

gavgrif
  • 15,194
  • 2
  • 25
  • 27