I want to add another row to my table when I click a button, but when I do click the button, nothing happens. I do not know if I am using addeventlistener incorrectly or if it is because of other errors in my javascript.
Here is my code:
HTML
<body>
<p style="text-align: center;"> hello </p>
<div id="Ingredients_Table_Div">
<table id="ingredients_Table" style="text-align: center">
<tr>
<th> ID </th><th>Ingredient Name</th><th>Quantity</th> <th>Delete Row</th>
</tr>
<tr>
<td>1</td> <td><input type="text" name="Ingredient[0][Ingre]"></td> <td><input type="text" name="Ingredient[0][Quantity]" ></td>
<td><!--<img src="trashcan" class="Delete">--></td>
</tr>
<tr id="adding_Row_Ingredients">
<td>Add Row</td> <td ><span id="add_button_ing">+</span></td>
</tr>
</table>
</div>
<script src="ADDRecipe.js"></script>
</body>
Javascript
let addbtn_ing = document.getElementById('add_button_ing');
let addbtn_ing_row = document.getElementById('adding_Row_Ingredients');
let ingredients_Table = document.getElementById('ingredients_Table');
addbtn_ing.addEventListener("click", () => {
let newRow = document.createElement("tr");
let rowIndex = ingredients_Table.rows.length - 2;
let rowID_Display = ingredients_Table.rows.length -1;
newRow.innerHTML = `
<td> ${rowID_Display} </td>
<td><input type="text" name="Ingredient[${rowIndex}][Ingre]"></td>
<td><input type="text" name="Ingredient[${rowIndex}][Quantity]" ></td>
<td><img src="trash_bin.png" class="Delete" alt="delete"></td>
`;
ingredients_Table.insertBefore( newRow, addbtn_ing_row);
})
3
Answers
Look in the console for your error.
Browsers will automatically create a
tbody
wrapper for your rows if you do not explicitly create one. This is causing problems when you try to insert a new row becauseaddbtn_ing_row
is not a child ofingredients_Table
.Try this markup instead.
HTML tables have a special native way for expansion, like this…
Try this method instead of inserting HTML.
as per mdn
here,
ingredients_Table.insertBefore( newRow, addbtn_ing_row);
addbtn_ing_row isn’t a child of<table>
. It is a child of<tbody>
encapsulated automatically by the browser.So to make this work select the child of the table instead of the table itself
i.e: