Search code examples
javascriptjquerycsseventhandler

Selecting dynamically given Ids with Jquery doesn't work


I have to do a website for university in which I load data from a database in a table. My table looks like this: https://dl.dropboxusercontent.com/u/6265197/Table.png

First I load the content from the database and create a table.

...
$.each(data, function (index, item) {
var counter = index;
counter++;
...
table += '<td><a href="#" ' + 'id=edit' + counter + '><img src="img/edit-icon.png"' + '</a> </td>';
table += '<td><a href="#" ' + 'id=delete' + counter + '><img src="img/delete-icon.png"' + ' ></a> </td>';
...

I give the buttons on the right unique ID which works.

My intention is that if "edit1" is pressed I can grab "name1" to work with it and find it in the database.

I tried this for example which only gives me an empty string on the console.

...
for (var x = 1; x <= 2; x++) {
    $('body').on('click', '#edit' + x, function () {
        console.log($('#name' + x).text());
    });
...

This one works basically.. and give me the String ( A Long Way Down ) on the console.

...
for (var x = 1; x <= 2; x++) {
    $('body').on('click', '#edit' + x, function () {
        console.log($('#name1').text());
    });
...

I hope you have an answer for me.

Greetings Andreas


Solution

  • You should learn Event Delegation.

    You can use custom data-* attributes to set value. Then use .data() to fetch it.

    Example code

    table += '<td><a href="#" class="edit" data-id="' + counter + '"><img src="img/edit-icon.png"' + '</a> </td>';
    table += '<td><a href="#" class="delete" data-id="' + counter + '"><img src="img/delete-icon.png"' + ' ></a> </td>';
    
    $(document).on('click', ".edit", function(event){
        event.preventDefault();
        var id = $(this).data('id');
        var text = $('#name' + id).text()
        console.log(text);
    });
    

    In place of document you should use closest static container.

    The 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, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.