2

I am generating a table and when I create the rows I have a for loop like this:

 for (var i = 0 ; i < myList.length ; i++) {
     var row$ = $('<tr/>');
     for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
         if (columns[colIndex] == 'web_id'){
          cellValue = "<a onclick='showMoreData('myList[i][columns[colIndex]]')'>" + myList[i][columns[colIndex]] + "</a>"
         }
         else {
              var cellValue = myList[i][columns[colIndex]];
         }

         if (cellValue == null) { cellValue = ""; }

         row$.append($('<td/>').html(cellValue));
     }
     $(".table").append(row$);

but this isn't working, what do I need to do to add an onclick event based on the row's content in a column so that I can add a dynamic link?

1
  • 2
    Nested single quotes may be the problem. Try cellValue = "<a onclick=\"showMoreData('myList[i][columns[colIndex]]')\">" + myList[i][columns[colIndex]] + "</a>" Commented Jul 18, 2016 at 18:20

1 Answer 1

1

You can create an A element, bind data to it and then you need to create event delegation and bind it to the table:

for (var i = 0 ; i < myList.length ; i++) {
    var row$ = $('<tr/>');

    for (var colIndex = 0 ; colIndex < columns.length ; colIndex++) {
        var cellValue = '';
        if (columns[colIndex] == 'web_id'){
            // Set a data attribute with the colindex and add the class 'web_id' for the event delegation
            cellValue = "<a href=\"\" class=\"web_id\" data-index=\"" + myList[i][columns[colIndex]] + "\">" + myList[i][columns[colIndex]] + "</a>";
         } else {
             cellValue = myList[i][columns[colIndex]];
         }

        if (cellValue == null) { cellValue = ""; }

        row$.append($('<td/>').html(cellValue));
    }

    $(".table").append(row$);
}

// Bind a click event for every .web_id element in the table 
$('.table').on('click', '.web_id', function(e) {
    e.preventDefault();

    // You can put here the logic of the 'showMoreData()' function
    alert( $(this).data('index') ); 
});

This replace the need to add onclick to the A elements in the table, because I added a data attribute called data-index - This attribute will be available via the jquery's .data() function.

I bind the click event using the event-delegation approach, which attaches an event handler to only one element, the .table, and the event only needs to bubble up one level (from the clicked .web_id to '.table'). Reference

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.