1

My JavaScript is supposed to add elements from an array to a table with each iteration of for loop. However, when I load my HTML page into FireFox, nothing of the sort happens. The table just stays the way I have created it in HTML. What can be the issue here? The code that I inserted into the JavaScript can be found at https://www.w3schools.com/jsref/met_table_insertrow.asp

<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta charset="UTF-8">
        <title>Classic Swedish Pancakes Recipe</title>
        <link href="HW5Part1.css" type="text/css" rel="stylesheet"/>


    </head>
        <body>
            <h1>Classic Swedish Pancakes</h1>

            <table id = "myTable" class="ingredients">
                <tr>
                    <th>Ingredient</th>
                    <th>Quantity</th>
                </tr>


            </table>
            <script>
                    //Creating an array with ingredient (ingredient followed by its quantity
                    var ingredients = new Array(‘separated eggs’, '3', 
                                                'whole milk', '1 cup', 
                                                'melted unsalted butter', '4 Tbsp.', 
                                                'sugar', '2 Tbsp.', 
                                                'vanilla extract', '1 tsp.', 
                                                'table salt', '1/4 tsp.', 
                                                'all-purpose flour', '1 cup', 
                                                'butter', '2 tsp.');


                    //Assigning a variable to our table
                    var table = document.getElementById("myTable");
                    //Creating a for loop with 8 iterations
                        for (var i = 0; i <8; i++) {
                            var row = table.insertRow(i+1);
                            var cell1 = row.insertCell(0);
                            var cell2 = row.insertCell(1);
                            cell1.outerHTML = ingredients.item(i*2);
                            cell2.outerHTML = ingredients.item(i*2+1);}
            </script>
     </body>
</html>
3
  • 1
    I dunno about you, but I don't think ‘separated eggs’ looks right. Commented Oct 1, 2019 at 22:12
  • ingredients.item(i*2), You don't access arrays elements like this, use [] instead Commented Oct 1, 2019 at 22:24
  • Always check the error console . Start there and fix the multitude of syntax errors there. Commented Oct 1, 2019 at 22:37

4 Answers 4

2

The issue is that item is not defined.

What you need is arrays within the ingredients array, as so:

var ingredients = [
    ['separated eggs', '3'],
    ['whole milk', '1 cup'],
    ['melted unsalted butter', '4 Tbsp.'],
    ['sugar', '2 Tbsp.'],
    ['vanilla extract', '1 tsp.'],
    ['table salt', '1/4 tsp.'],
    ['all-purpose flour', '1 cup'],
    ['butter', '2 tsp.']
];

From there, you can create your loop to access each item individually.

In it, you first need to grab i, followed by 0 or 1. 0 for the ingredient and 1 for the quantity.

ingredients[i][0]

//Creating an array with ingredient (ingredient followed by its quantity
var ingredients = [
    ['separated eggs', '3'],
    ['whole milk', '1 cup'],
    ['melted unsalted butter', '4 Tbsp.'],
    ['sugar', '2 Tbsp.'],
    ['vanilla extract', '1 tsp.'],
    ['table salt', '1/4 tsp.'],
    ['all-purpose flour', '1 cup'],
    ['butter', '2 tsp.']
];


//Assigning a variable to our table
var table = document.getElementById("myTable");
//Creating a for loop with 8 iterations
for (var i = 0; i < ingredients.length; i++) {
    var row = table.insertRow(i + 1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = ingredients[i][0];
    cell2.innerHTML = ingredients[i][1];
}
<!DOCTYPE html>
<html lang="en-us">
    <head>
        <meta charset="UTF-8">
        <title>Classic Swedish Pancakes Recipe</title>
        <link href="HW5Part1.css" type="text/css" rel="stylesheet"/>


    </head>
        <body>
            <h1>Classic Swedish Pancakes</h1>

            <table id="myTable" class="ingredients">
                <tr>
                    <th>Ingredient</th>
                    <th>Quantity</th>
                </tr>


            </table>
            </body>
            </html>

Please note that the quotes surrounding seperated eggs are special characters and will break your code.

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

3 Comments

Your solution works. Thank you very much! As for the ".item". It was mentioned as one of the methods for retrieving elements from an array by my textbook. I guess it is wrong.
Better to use ingredients.length in the loop initialization, instead of hard coding 8.
@JonP True. Just fixed it!
0

Well you have some issues.

The "seperated eggs" doesnt look like a valid string. I'd double check on that.

Also ".item" is not a valid function for an array. Just use the index:

cell1.outerHTML = ingredients[(i*2)];

3 Comments

I have fixed "separated eggs" string and tried to use your index. However, it still does not work. ".item" is a valid function for an array according to the text I am using. The text is "JAVASCRIPT & JQUERY Interactive Front-End Web Development " by John Duckett
@Dante .item comes from jQuery. You have not included jQuery based on the code you have given us, and until this comment you have given us no indication that you are using jQuery.
@Jon P My textbook did not mention that ".item" was jQuery and not JavaScript or I got something confused, my bad.
0

First of all, the apostrophes you used around 'separated eggs' are some special character and not being read by my text editor. Change those to some regular ' characers.

Next, I got an error that igredients.item is not a function. I'd never heard of that before either. Just change it to ingredients[i*2]. See the code below:

var ingredients = new Array('separated eggs', '3',
                            'whole milk', '1 cup',
                            'melted unsalted butter',Tbsp.',
                            'sugar', '2 Tbsp.',
                            'vanilla extract', '1 tsp.',
                            'table salt', '1/4 tsp.',
                            'all-purpose flour', '1 cup',
                            'butter', '2 tsp.');

var table = document.getElementById("myTable");

for (var i = 0; i <8; i++) {
    var row = table.insertRow(i+1);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = ingredients[i*2];
    cell2.innerHTML = ingredients[i*2+1];
}

Also, just as a tip, you can write your array much nicer like this:

   var ingredients = [
      'separated eggs', '3',
      'whole milk', '1 cup',
      'melted unsalted butter',Tbsp.',
      'sugar', '2 Tbsp.',
      'vanilla extract', '1 tsp.',
      'table salt', '1/4 tsp.',
      'all-purpose flour', '1 cup',
      'butter', '2 tsp.'
   ]

Comments

0

I'm going to expand on Michelles great answer and modernize it a little.

I'm going to replace the array of array with a more meaningful array of objects. Then I'll use a template literal for the content.

Finally We'll only update the DOM once as each DOM update causes a redraw, which can get expensive.

//Creating an array with ingredient (ingredient followed by its quantity
var ingredients = [
  {ingredient:'separated eggs', amount:'3'},
  {ingredient:'whole milk', amount: '1 cup'},
  {ingredient:'melted unsalted butter', amount: '4 Tbsp.'},
  {ingredient:'sugar', amount: '2 Tbsp.'},
  {ingredient:'vanilla extract', amount: '1 tsp.'},
  {ingredient:'table salt', amount: '1/4 tsp.'},
  {ingredient:'all-purpose flour', amount: '1 cup'},
  {ingredient:'butter', amount: '2 tsp.'}
];


//Assigning a variable to our table
var table = document.getElementById("myTable");
var newHTML = "";

//iterate the array
ingredients.forEach(function(item){
  newHTML += `
<tr>
   <td>${item.ingredient}</td>
   <td>${item.amount}</td>
</tr>`
});
//finally update the table
table.innerHTML += newHTML;
<h1>Classic Swedish Pancakes</h1>

<table id="myTable" class="ingredients">
  <tr>
    <th>Ingredient</th>
    <th>Quantity</th>
  </tr>

1 Comment

I do realize that using for loop is not necessary, that was just directions for my assignment to practice for loop in JavaScript.

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.