Everything is working fine in below code. But when I want to put a greater quantity than exiting quantity in a specific products, It returns me negative value. Where to write the code to return the following two reuslts?
(1). I want to put value up to 0.
(2). If It goes below 0, alert with “No product in Store”.
const inputValue = id => { const input = document.getElementById(id); const inputValue = input.value; input.value = ''; return inputValue; } const addProduct = () => { const productName = inputValue('product-name'); const productQnt = inputValue('product-quantity'); // console.log(productName, productQnt); // check typeof input value // console.log(typeof productName, typeof productQnt) // check input type const number = Number(productQnt); if (!isNaN(productName || !Number.isInteger(number))) { alert('nai'); return; } // console.log(Number.isInteger(number)); setProductInLocalStorage(productName, productQnt); // showdata on table at console // getLocalStorageData(); displayProduct(); } // get items const getLocalStorageData = () => { const products = localStorage.getItem('All-Products'); const parseProducts = JSON.parse(products); return parseProducts; } // set items const setProductInLocalStorage = (productName, productQnt) => { let products = getLocalStorageData(); if (!products) { products = {}; } // add updated quantities if (products[productName]) { products[productName] = parseInt(products[productName]) + parseInt(productQnt) } else { products[productName] = productQnt; } localStorage.setItem('All-Products', JSON.stringify(products)); }; // display product on UI const displayProduct = () => { const allProducts = getLocalStorageData(); const section = document.getElementById('all-products'); section.textContent = ''; for (const product in allProducts) { const name = product; const quantity = allProducts[product] const div = document.createElement('div'); div.innerHTML = ` <div class="shadow-sm p-3 mb-2 bg-body rounded"> <span class="fs-4">${name}</span> Quantity:<small class="fw-bold"> ${quantity} </small> </div> `; section.appendChild(div); } } // call display products to display on UI displayProduct();
Advertisement
Answer
Code written below is maybe helpful. And i thought your way of checking productQnt whether is a Integer seems doesn’t work, therefore i show you one valid way meanwhile. Hope it shall be useful to you.
// check input type const number = Number(productQnt); if(!productName || !Number.isInteger(number)){ alert('nai'); return; } if (number < 0) { alert ("No product in Store"); return; }