Igor Shvets
Igor Shvets

Reputation: 547

Why is not the value added from input fields to the array?

I created a form with fields name, price, count and the Add button. When clicking on this button, the product should be added to the array of products of the "Shop" class. But this does not happen and tell me whether I'm building the code structure correctly ?

class Product {
    constructor() {
        this.name = document.getElementById("name").value;
        this.count = document.getElementById("price").value;
        this.price = document.getElementById("count").value;
    }

}
class Shop {
    constructor() {
        this.products = [];

    }

    //method for adding a product
    addProduct(newProduct) {
        this.products.push(newProduct);
    }
}
const shop = new Shop();
const buttAdd = document.getElementById("add");
buttAdd.addEventListener("click", (e) => {
    shop.addProduct(new Product(this.name, this.count, this.price));

}, false);
console.log(shop.products);
   <form>
            <label for="name" >Name of product</label>
            <input type="text"  id="name" class="input-product">
            <label for="price">Price of product</label>
            <input type="text"  id="price" class="input-product">
            <label for="count">Count of product</label>
            <input type="text"  id="count" class="input-product">
            <button id="add">Add</button>
        </form>

Upvotes: 1

Views: 42

Answers (1)

vizsatiz
vizsatiz

Reputation: 2163

There is no issue in your code. It's just that your print statement should be inside onclick event. You should write your asynchronous prints within callbacks in JS

class Product {
    constructor() {
        this.name = document.getElementById("name").value;
        this.count = document.getElementById("price").value;
        this.price = document.getElementById("count").value;
    }

}
class Shop {
    constructor() {
        this.products = [];

    }

    //method for adding a product
    addProduct(newProduct) {
        this.products.push(newProduct);
    }
}
const shop = new Shop();
const buttAdd = document.getElementById("add");
buttAdd.addEventListener("click", (e) => {
    shop.addProduct(new Product(this.name, this.count, this.price));
   console.log(shop.products);
}, false);
   <form>
            <label for="name" >Name of product</label>
            <input type="text"  id="name" class="input-product">
            <label for="price">Price of product</label>
            <input type="text"  id="price" class="input-product">
            <label for="count">Count of product</label>
            <input type="text"  id="count" class="input-product">
            <button id="add">Add</button>
        </form>

Upvotes: 1

Related Questions