Search code examples
jqueryajaxappendhtml-tablehead

JQuery: Append to table head


So I'm trying to append data from the Url to the head of the table. The data called from the URL is a string list. So as you can see I'm trying to go through each value in the list and then append it to the head of my table, 'data'. But when I run the code nothing is appended. I know the data is going in because the window alert is displaying each of the strings.

JQuery:

$(document).ready(function () {
    $.ajax({
        url: 'http://..../api/Dynamic?table=table1',
        dataType: 'Json',
        success: function (tableResults) {
            var count = 0;
            $.each(tableResults, function () {
                window.alert(this);
                $('#data th:last-child').append('<th><a id="count">' + this + '</a></th>');
                count++;
            });
        }
    });
});

HTML:

<table id="data" border="1" align="center" width="95%">
        <thead>
            <tr>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

Any suggestions?


Solution

  • If the tableResults is an array of string you can use directly the each parameters and avoid the count variable like in the following snippet (use after instead of append because the new th elements must follow and not be child of the last th):

    //
    // if thead does not exist
    //
    if ($('#data thead').length == 0) {
      $('#data').append($('<thead/>'));
    }
    
    $.each(['email', 'address', 'country'], function (index, value) {
      if ($('#data th:last-child').length == 0) {
         //
         // if there are no th
         //
        $('#data thead').append('<th><a id="count' + index + '"</a>' + value + '</th>');
      } else {
        $('#data th:last-child').after('<th><a id="count' + index + '"</a>' + value + '</th>');
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <table id="data" border="1" align="center" width="95%">
      <thead>
        <tr>
        </tr>
      </thead>
      <tbody>
      </tbody>
    </table>