-2

I have the below code which should be taking the value of each data result and publishing it to a HTML Table. I can't figure out why the below isn't working:

<html>
  <head>
    <script type="text/javascript">
    data = { d : {
        results: [
            { Title: 'Title1', Description: 'Description1', Status: 'Status1', Complete: 'Complete1' },
            { Title: 'Title2', Description: 'Description2', Status: 'Status2', Complete: 'Complete2' },
            { Title: 'Title3', Description: 'Description3', Status: 'Status3', Complete: 'Complete3' },
            { Title: 'Title4', Description: 'Description4', Status: 'Status4', Complete: 'Complete4' } ] } };

    data.d.results.push({Title: 'Title5', Description: 'Description5', Status: 'Status5', Complete: 'Complete5'});


    $(document).ready(function() {
        for (var i = 0; i < data.d.results.length; i++) {
            item = data.d.results[i];
            str  = '<tr><td>' + item.Title + '</td><td> ' + item.Description + '</td><td>' + item.Status + '</td><td>' + item.Complete + '</td></tr>';
            $('#mytab tr').last().after(str);
       }
    });

    </script>
  </head>
  <body>
  <table id="mytab">
    <tr>
      <td>Task Title</td> <td>Description</td> <td>Task Status</td> <td>% Complete</td>
    </tr>
  </table>
  </body>
</html>
Liam
  • 27,717
  • 28
  • 128
  • 190
Jaron787
  • 562
  • 1
  • 11
  • 29

2 Answers2

1

Extending Patrick's idea here. You can ensure JS executes after DOM is loaded by using:

$(document).ready(function() {
   // execute your JavaScript code
   // that depends on DOM
});
Priya Ranjan Singh
  • 1,567
  • 1
  • 15
  • 29
  • I've done that but i keep getting: ReferenceError: $ is not defined in the console – Jaron787 Mar 06 '17 at 14:48
  • In your comments section in question everyone asked you to include jQuery. Your code depends on it. Look at this question and accepted answer carefully. http://stackoverflow.com/questions/7496789/how-to-include-jquery-in-another-javascript-file – Priya Ranjan Singh Mar 06 '17 at 14:58
0

Your script is running before your table is rendered in the DOM. Try moving your script tag from the <head> to right before the closing </body> tag.

Patrick Hund
  • 19,163
  • 11
  • 66
  • 95