Skip to content

Commit 52c98f1

Browse files
committed
Create AddProduct button
1 parent 33d1511 commit 52c98f1

File tree

2 files changed

+32
-14
lines changed

2 files changed

+32
-14
lines changed

projects/tip-calculator/index.html

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,22 +35,9 @@ <h1>Tip Calculator</h1>
3535
<span></span>
3636
</td>
3737
</tr>
38-
<tr>
39-
<td>
40-
<input type="text" />
41-
</td>
42-
<td>
43-
<input type="number" />
44-
</td>
45-
<td>
46-
<input type="number" />
47-
</td>
48-
<td>
49-
<span></span>
50-
</td>
51-
</tr>
5238
</tbody>
5339
</table>
40+
<button class="btn-success" id="add-product">Add Product +</button>
5441
<br />
5542
<label for="tip">Tip percentage:</label>
5643
<input type="number" id="tip" />

projects/tip-calculator/index.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
const productTable = document.getElementById("product-table");
22
const productRows = productTable.children;
33

4+
const btnAddProduct = document.getElementById("add-product");
45
const tipInput = document.getElementById("tip");
56

67
const btnCalculate = document.getElementById("calculate");
@@ -10,6 +11,35 @@ const subtotalSpan = document.getElementById("subtotal");
1011
const finalTipSpan = document.getElementById("final-tip");
1112
const totalSpan = document.getElementById("total");
1213

14+
let totalRows = 0;
15+
16+
function addProduct() {
17+
totalRows++;
18+
const currentRow = totalRows;
19+
const htmlString = `
20+
<td>
21+
<input type="text" />
22+
</td>
23+
<td>
24+
<input type="number" />
25+
</td>
26+
<td>
27+
<input type="number" />
28+
</td>
29+
<td>
30+
<span></span>
31+
</td>
32+
`;
33+
34+
const row = document.createElement("tr");
35+
row.innerHTML = htmlString;
36+
const priceInput = row.children[1].firstElementChild;
37+
const unitInput = row.children[2].firstElementChild;
38+
priceInput.addEventListener("focusout", () => calculateRow(currentRow));
39+
unitInput.addEventListener("focusout", () => calculateRow(currentRow));
40+
productTable.appendChild(row);
41+
}
42+
1343
function calculateRow(row) {
1444
const priceValue = productRows[row].children[1].firstElementChild.value;
1545
const unitValue = productRows[row].children[2].firstElementChild.value;
@@ -66,5 +96,6 @@ for (let row = 0; row < productRows.length; row++) {
6696
unitInput.addEventListener("focusout", () => calculateRow(row));
6797
}
6898

99+
btnAddProduct.addEventListener("click", addProduct);
69100
btnCalculate.addEventListener("click", calculateTotal);
70101
btnClean.addEventListener("click", cleanTotal);

0 commit comments

Comments
 (0)