Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function attachEvents() {
- const BASE_URL = 'http://localhost:3030/jsonstore/grocery/';
- const inputDOMSelectors = {
- product: document.getElementById('product'),
- count: document.getElementById('count'),
- price: document.getElementById('price')
- }
- const otherDOMSelectors = {
- addProductsBtn: document.getElementById('add-product'),
- updateProductBtn: document.getElementById('update-product'),
- loadProductsBtn: document.getElementById('load-product'),
- productsContainer: document.getElementById('tbody')
- }
- let currentProducts = [];
- let productToEdit = {};
- otherDOMSelectors.loadProductsBtn.addEventListener('click', loadProductsHandler);
- otherDOMSelectors.updateProductBtn.addEventListener('click',updateProductHandler);
- function loadProductsHandler(event) {
- if (event) {
- event.preventDefault();
- }
- fetch(BASE_URL)
- .then((response) => response.json())
- .then((allProductsResponse) => {
- currentProducts = Object.values(allProductsResponse);
- console.log(currentProducts);
- for (const {product, count, price, _id} of currentProducts) {
- const tableRow = createElement('tr', '', otherDOMSelectors.productsContainer);
- tableRow.id = _id;
- createElement('td', product, tableRow, '', ['name']);
- createElement('td', count, tableRow, '', ['count-product']);
- createElement('td', price, tableRow, '', ['product-price']);
- const productOptionButtons = createElement('td', '', tableRow, '', ['btn']);
- const updateBtn = createElement('button', 'Update', productOptionButtons, '', ['update']);
- const deleteBtn = createElement('button', 'Delete', productOptionButtons, '', ['delete']);
- updateBtn.addEventListener('click', loadUpProductToUpdate);
- }
- })
- }
- function loadUpProductToUpdate () {
- const id = this.parentNode.parentNode.id;
- console.log(id);
- productToEdit = currentProducts.find((p)=> p._id ===id);
- for (const key in inputDOMSelectors) {
- inputDOMSelectors[key].value = productToEdit[key];
- console.log( inputDOMSelectors[key].value);
- }
- }
- function updateProductHandler (event){
- }
- }
- attachEvents()
- function createElement(type, content, parentNode, id, classes, attributes, useInnerHtml) {
- const htmlElement = document.createElement(type);
- if (content && useInnerHtml) {
- htmlElement.innerHTML = content;
- } else {
- if (content && type !== 'input') {
- htmlElement.textContent = content;
- }
- if (content && type === 'input') {
- htmlElement.value = content;
- }
- }
- if (id) {
- htmlElement.id = id;
- }
- if (classes && classes.length > 0) {
- htmlElement.classList.add(...classes);
- }
- if (parentNode) {
- parentNode.appendChild(htmlElement);
- }
- if (attributes) {
- for (const key in attributes) {
- htmlElement.setAttribute(key, attributes[key]);
- }
- }
- return htmlElement;
- }
Advertisement
Add Comment
Please, Sign In to add comment