0

I created an object with an array of products and I want to retrieve its value in a label in my html file but I don't know what's the right format. My javascript and html file are in separated files. Can someone help me with this. Thanks a lot!

const database = [
  {
    name: "test",
    brand: "test",
    description: "test desc",
    price: "100",
  },
  {
    name: "test2",
    brand: "test brand",
    description: "test desc2",
    price: "200",
  },
  {
    name: "test3",
    brand: "test brand",
    " description": "test desc3",
    price: "300",
  },
];

function addToCart() {
  return console.log(database[0].name)
}
<div class="card">
      <img src= "img/1.jpg" alt="Avatar">
      <div class="container">
        <span>
          <input type="text" placeholder="Enter items" id="productName" value=$database[0].name />
        <button onclick="addToCart()" id="addToCart">Buy</button>
      </div>
 </div>
CodeBug
  • 1,649
  • 1
  • 8
  • 23
Xev
  • 109
  • 1
  • 1
  • 12
  • What do you mean passing from a JS file to a HTML file? Are you maybe taking about [DOM manipulation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Manipulating_documents)? – M0nst3R Jul 03 '20 at 14:44
  • @GhassenLouhaichi Yes. I just don't know how to get or pass the value from my object and retrieve to my html element or what's the correct format to use to get the value. – Xev Jul 03 '20 at 14:52
  • 2
    Suggest you start with some javascript basics on how to set a value for an `` using javascript. You should have no problem finding tutorials for doing it. SO is not tutorial service to learn basics. It is expected you research the fundamentals yourself first – charlietfl Jul 03 '20 at 14:53
  • this require module if you know what is I can show the way but if you're beginner just go step by step – Umutambyi Gad Jul 03 '20 at 14:56
  • Does this answer your question? [Set Value of Input Using Javascript Function](https://stackoverflow.com/questions/5700471/set-value-of-input-using-javascript-function) – M0nst3R Jul 03 '20 at 14:57

1 Answers1

0

const database = [
  {
    name: "test",
    brand: "test",
    description: "test desc",
    price: "100",
  },
  {
    name: "test2",
    brand: "test brand",
    description: "test desc2",
    price: "200",
  },
  {
    name: "test3",
    brand: "test brand",
    " description": "test desc3",
    price: "300",
  },
];

function addToCart() {
document.getElementById('productName').value = database[0].name;
}
<div class="card">
      <img src= "img/1.jpg" alt="Avatar">
      <div class="container">
        <span>
          <input type="text" placeholder="Enter items" id="productName"/>
        <button onclick="addToCart()" id="addToCart">Buy</button>
      </div>
 </div>

try this. it will work

CodeBug
  • 1,649
  • 1
  • 8
  • 23