I am new to javascript and encountering an issue. When I use alert in my script, the output data is shown as [Object object]. The function below is called when the button (onClick
) is clicked. There are [Object object]
elements in the array. The last line of code, specifically innerHtml
, is not functioning properly.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="center">
<h1 align="center">Shop Basket</h2>
<script type="text/javascript" src="external.js"></script>
<table align="center">
<tr>
<th align="left">Price</th>
<th>Product</th>
<th></th>
</tr>
<script>
let products = [{
20: "ssd drive"
},
{
1100: "washing machine"
},
{
219: "tablet"
},
{
500: "monitor"
},
{
789: "i5 processor"
},
{
88: "sound card"
},
{
220: "logitech mouse"
},
{
219: "modecom keyboard"
},
{
900: "gtx 1060"
},
{
823: "rx 570"
}
];
let shopBasket = [];
function addToBasket(value) {
shopBasket.push(value);
alert(shopBasket);
document.getElementById("change").innerHtml = "" + shopBasket.length;
}
for (let i = 0; i < products.length; i++) {
for (let key in products[i]) {
document.write("<tr>");
document.write("<td>" + key + "</td>");
document.write("<td>" + products[i][key] + "</td>");
document.write('<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + products[i] + '\')"/></td>');
document.write("</tr>");
}
}
</script>
</table>
<center>
<a href="html-link.htm"><img src="shopbasket.jpg" title="basket" alt="basket"></a>
</center>
</div>
<p id="change"></p>
</body>
</html>
Best regards