-3

I am beginner with javascript and I have following problem. The output data when i am invoking alert in my script is [Object object]. Following function is invoked when the button is clicked(onClick). There are [Object object] elements in the array. And the last line of of code doesn't work properly, I mean, innerHtml.

<!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: "dysk ssd"
            },
            {
              1100: "pralka"
            },
            {
              219: "pad"
            },
            {
              500: "monitor"
            },
            {
              789: "i5 processor"
            },
            {
              88: "soundblaster"
            },
            {
              220: "mysz logitech"
            },
            {
              219: "klawiatura modecom"
            },
            {
              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>

Regards

  • 2
    provide the HTML too – ellipsis Mar 25 '19 at 09:06
  • 11
    `innerHtml` should be `innerHTML` – Adrian Mar 25 '19 at 09:06
  • 1
    Can you please explain what you want to do? – Ckappo Mar 25 '19 at 09:10
  • 1
    @Ckappo Looks like he's trying to show the array size on the page - precisely inside the `p` tag with id "change". – Adrian Mar 25 '19 at 09:15
  • 1
    @Adriani6 So your innerHTML fix should be the solution :-) – Ckappo Mar 25 '19 at 09:17
  • Separate HTML from CSS and JavaScript. Don't use `document.write`. Learn what a closure is. You'll soon learn that you have to think dynamically. Just a comment. – StackSlave Mar 25 '19 at 09:26
  • 1
    To address what 'object Object' means, it's just the default serialization of an Object. For example, converting a function to a string would yield 'object Function' etc. See the following for a more detailed description https://stackoverflow.com/a/25419538/11286273 – Sam James Apr 06 '19 at 18:51

1 Answers1

0

I guess you need to do a JSON stringify in your HTML file as the following:

document.write('<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + JSON.stringify(products[i]) +'\')"/></td>');

Then in your JS code add the JSON parsing as below:

shopBasket.push(JSON.parse(value));

Run the code snippet, just writing to the console with and without JSON.stringify you can see the difference:

let products = [ 
    {20: "dysk ssd"}, 
    {1100: "pralka"}, 
    {219: "pad"}, 
    {500: "monitor"},
    {789: "i5 processor"},
    {88: "soundblaster"},
    {220: "mysz logitech"}, 
    {219: "klawiatura modecom"},
    {900: "gtx 1060"}, 
    {823: "rx 570"}
];

for (let i = 0; i < products.length; i++) {
   for (let key in products[i]) {
      console.log('Without using stringifiy', '<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + products[i] + '\')"/></td>');
      console.log('With using stringifiy', '<td><input value="Add to ShopBakset" type="button" onClick="addToBasket(\'' + JSON.stringify(products[i]) + '\')"/></td>');
   }

   // just to write only the first element
   break;
}

And in your JavaScript function if you parse the string again:

AddToBasket('{"20":"dysk ssd"}');

function AddToBasket(value) {
  let parsedBasket = JSON.parse(value);
  
  console.log(parsedBasket);
  
  // your code
}

Update: Okay, so let's move all the JavaScript code to your external file and forget about document write, first add an ID to your table:

<table id="productsTable" align="center">

Then from the external JS file do the following:

let table = document.getElementById('productsTable');

for (let i = 0; i < products.length; i++) {
    for (let key in products[i]) {
        table.innerHTML += "<tr>";
        table.innerHTML += "<td>" + key + "</td>";
        table.innerHTML += "<td>" + products[i][key] + "</td>";
        table.innerHTML += "<td><input value=\"Add to ShopBakset\" type=\"button\" onClick=\"addToBasket(" + formatProduct(products[i]) + ")\"/></td>";
        table.innerHTML += "</tr>";
    }
}

function formatProduct(product) {
   return JSON.stringify(product).replace(/\"/g, '\'')
}

This will resolve your unexpected token issue.

In your addToBasket function you can write to the console the result:

function addToBasket(value) { 
   console.log('json object', value);

   // ... your code
}

Which will print the following JSON object:

JSON object

norbitrial
  • 14,716
  • 7
  • 32
  • 59