-3

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>
8
  • 1
    I couldn't reproduce the problem but I had to import jquery which you might be missing. Commented Mar 6, 2017 at 14:38
  • Could you please share the browser console logs if any?? Commented Mar 6, 2017 at 14:38
  • Thanks. I've amended that. Still not working though Commented Mar 6, 2017 at 14:38
  • Did you check your console for errors? It tells you what the problem is. Commented Mar 6, 2017 at 14:42
  • 1
    ReferenceError: $ is not defined Commented Mar 6, 2017 at 14:45

2 Answers 2

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

I've done that but i keep getting: ReferenceError: $ is not defined in the console
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. stackoverflow.com/questions/7496789/…
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.