0

I am creating a simple Online Grocery Sotre. I have one HTML file that the user uses to select the items and amounts they want. The HTML file has a javascript file associated that takes the values input by the user and places it into an array. This works fine.

My Goal -> is to then use the json object created and display it or use it in another html file that I will use to display the users order. I am have tried different way to do this but I can't import the json object created.

HTML FORM

  </div>

      <div class="row">
                <div class="column">
                    <img src="images/vegetables.jpg" alt="vegetables" width="250" height="166"><br>
                    <select name="veggies" id="veggies">
                    <option value="none">None</option>
                    <option value="carrot">Carrot</option>
                    <option value="tomato">Tomato</option>
                    <option value="potato">Potato</option>
                    <option value="pepper">pepper</option>
                    </select>
                    <input type="number" id="quantity1" name="quantity1" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/meats.jpg" alt="meats" width="250" height="166"><br>
                    <select name="meats" id="meats">
                    <option value="none">None</option>
                    <option value="chicken">Chicken</option>
                    <option value="beef">Beef</option>
                    <option value="pork">Pork</option>
                    <option value="fish">fish</option>
                    </select>
                    <input type="number" id="quantity2" name="quantity2" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/breads.jpg" alt="breads" width="250" height="166"><br>
                    <select name="breads" id="breads">
                    <option value="none">None</option>
                    <option value="whiteBread">White Bread</option>
                    <option value="WheatBread">Wheat Bread</option>
                    <option value="baguette">Baguette</option>
                    <option value="cake">Cake</option>
                    </select>
                    <input type="number" id="quantity3" name="quantity3" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/sweets.jpg" alt="sweets" width="250" height="166"><br>
                    <select name="sweets" id="sweets">
                    <option value="none">None</option>
                    <option value="chocolate">Chocolate</option>
                    <option value="candy">Candy</option>
                    <option value="cookies">Cookies</option>
                    <option value="IceCream">Ice Cream</option>
                    </select>
                    <input type="number" id="quantity4" name="quantity4" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/softDrinks.jpg" alt="softDrinks" width="250" height="166"><br>
                    <select name="drinks" id="drinks">
                    <option value="none">None</option>
                    <option value="coke">Coke</option>
                    <option value="pepsi">Pepsi</option>
                    <option value="7up">7-Up</option>
                    <option value="iceTea">Ice Tea</option>
                    </select>
                    <input type="number" id="quantity5" name="quantity5" min="1" max="5">
                </div>
                <div class="column">
                    <img src="images/eggs.jpg" alt="eggs" width="250" height="166"><br>
                    <select name="eggs" id="eggs">
                    <option value="none">None</option>
                    <option value="eggs">Eggs</option>
                    <option value="milk">Milk</option>
                    <option value="cheese">Cheese</option>
                    </select>
                    <input type="number" id="quantity6" name="quantity6" min="1" max="5">
                </div>

            </div>
            <br>
            <button type="submit" class="button button2" id="btn1" >Submit</button>

            <br><br><br>
            <br>

This is the js file associated to this HTML form that captures the values and creates the json object.

document.getElementById("btn1").onclick = function(){Purchase()}
document.getElementById("pay").onclick = function(){Cart()}


var products = new Array();
var amount = new Array();

function Purchase(){

    // veggies value and amount
    var veggies = document.getElementById('veggies').value 
    var veggiesAmount = document.getElementById('quantity1').value

    // meats value and amount
    var meats = document.getElementById('meats').value 
    var meatsAmount = document.getElementById('quantity2').value

    // breads value and amount 
    var breads = document.getElementById('breads').value 
    var breadsAmount = document.getElementById('quantity3').value

    // sweets value and amount 
    var sweets = document.getElementById('sweets').value 
    var sweetsAmount = document.getElementById('quantity4').value

    // soft drinks value and amount 
    var drinks = document.getElementById('drinks').value 
    var drinksAmount = document.getElementById('quantity5').value

    // eggs drinks value and amount 
    var eggs = document.getElementById('eggs').value 
    var eggsAmount = document.getElementById('quantity6').value

    // new elements to array
    products.push(veggies)
    amount.push(veggiesAmount)

    products.push(meats)
    amount.push(meatsAmount)

    products.push(breads)
    amount.push(breadsAmount)

    products.push(sweets)
    amount.push(sweetsAmount)

    products.push(drinks)
    amount.push(drinksAmount)

    products.push(eggs)
    amount.push(eggsAmount)
    
    
    console.log(products)
    console.log(amount)



}

When I run the file normal this is the image of what I get.

JSON Object

I want to display that json object on this HTML file.

Display form

4
  • Save the data in localStorage, then you can read it in the other file. Commented Jan 14, 2021 at 0:23
  • How can I save the Json file in local storage ? Is their a method to do that? Commented Jan 14, 2021 at 1:16
  • ... = function(){Purchase()} creates a useless wrapper function, more efficient to just assign a reference to Purchase directly: ... = Purchase. Commented Jan 14, 2021 at 1:29
  • localStorage.setItem("name", JSON.stringify(object)); Commented Jan 14, 2021 at 1:34

1 Answer 1

1

you don't have to get every element value, there is a more generic way to do that. try that solution.

SOLUTION. #1

javascript snippet

document.getElementById("btn1").onclick = function () {
  purchase();
};

function getAllValues() {
  const ProductObject = [];
  let components = document.querySelectorAll(".column");
  let itemsList = Array.from(components);

  itemsList.forEach((item) => {
    let productName = item.getElementsByTagName("select")[0].value;
    let productAmount = item.getElementsByTagName("input")[0].value;
    if (productName !== "none") {
      ProductObject.push({
        name: productName,
        amount: productAmount
      });
    }
  });

  return ProductObject;
}

function purchase() {
  let selectedProducts = getAllValues();
  
  let table = document.querySelector("#product_table");
  let tbody = document.querySelector("#product_table tbody");
  let tableBody = document.createElement("tbody");
  let htmlList = [];

  // reset table before update.
  tbody && table.removeChild(tbody);

  Object.values(selectedProducts).forEach((product) => {
    htmlList.push(
      `<tr>
        <td> ${product.name} </td>
        <td> ${product.amount} </td>
      </tr>`
    );
  });

  tableBody.innerHTML = htmlList.join("");
  table.appendChild(tableBody);
}

SOLUTION. #2

document.getElementById("btn1").onclick = function () {
  purchase();
};

[...document.querySelectorAll('input[type="number"]')].forEach((i) =>
  i.setAttribute("disabled", true)
);

let selectedProducts = {};

let productForm = document.getElementById("ProductForm");
productForm.addEventListener("change", updateProducts);

function updateProducts(event) {
  let productType = event.target.name;

  if (event.target.type === "number") {
    let currentProduct = event.target.previousElementSibling.name;

    selectedProducts[currentProduct] = {
      ...selectedProducts[currentProduct],
      amount: event.target.value
    };
  } else {
    let siblingInput = event.target.nextElementSibling;
    siblingInput.removeAttribute("disabled");
    selectedProducts[productType] = {
      amount: "",
      name: event.target.value
    };
  }
}

function purchase() {
  let table = document.querySelector("#product_table");
  let tbody = document.querySelector("#product_table tbody");
  let tableBody = document.createElement("tbody");
  let htmlList = [];

  // reset table before update.
  tbody && table.removeChild(tbody);

  Object.values(selectedProducts).forEach((product) => {
    htmlList.push(
      `<tr>
        <td> ${product.name} </td>
        <td> ${product.amount} </td>
      </tr>`
    );
  });

  tableBody.innerHTML = htmlList.join("");
  table.appendChild(tableBody);
}

and for the HTML snippet add an id to the parent of the controls. to capture the event propagation.

<body>
    <div class="row" id="ProductForm"> // id="ProductForm"
      <div class="column">
         .....

live working demo

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.