skip to Main Content

How do I keep the clicked button disabled even when I reload the page? Default is not disabled, but after 10 click it should go disabled, and then stay disabled after reload the page.
Its an array with products where the stock is 10. When the stock is out the button should be disabled. Thanks in advance!

const wrapper = document.querySelector('.grid')
let lager = 10
let productsArray= []
let datavar = ''

async function getProducts(){
  try{
    const baseURL = 'https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/'
    const url = baseURL + 'Products.json'
    const response = await fetch(url)
    let data = await response.json()
    console.log(data)
    productsArray.push(data)
    datavar = Object.keys(data)
    console.log(datavar)
    console.log(productsArray)
    
    
  }catch(error){
    console.log(error)
  }
  

  }

getProducts()


let cartNr = document.getElementById('cartNr')
const lang1 = document.querySelector('.lang1')
cartNr = 1

let products = [
    {
        id: 0,
        namn: 'Sneaker1',
        img: '//shelta.se/pub_images/original/DV1129-300_1.jpg?timestamp=1677759773',
        pris: 1500,
        lager: 10,
        inCart: 0
    },
    {
        id: 1,
        namn: 'Sneaker2',
        img: 'https://shelta.se/pub_images/original/AH6789-006_1.jpg',
        pris: 1500,
        lager: 10,
        inCart: 0
    },
    {
        id: 2,
        namn: 'Sneaker3',
        img: 'https://shelta.se/pub_images/original/DV1129-001_1.jpg?timestamp=1673044814',
        pris: 1500,
        lager: 10,
        inCart: 0
    },
    {
        id: 3,
        namn: 'Sneaker4',
        img: 'https://shelta.se/pub_images/original/AH6789-001_1.jpg?timestamp=1609192138',
        pris: 1500,
        lager: 10,
        inCart: 0
    },
    {
        id: 4,
        namn: 'Sneaker5',
        img: 'https://shelta.se/pub_images/original/DM2361-100_0.jpg?timestamp=1628091117',
        pris: 1500,
        lager: 10,
        inCart: 0
    }
]



const euro = document.querySelectorAll('.euro')


for(let i = 0; i < euro.length; i++ ){
    
    euro[i].addEventListener('click', (e) => {
        e.preventDefault()
        
        cartNumbers(products[i])
        totalCost(products[i])
       
         if(products[i].inCart > 9 || products[i].lager < 1){
           const disabled =  euro[i].disabled = true
           localStorage.setItem('disabled', disabled )
           let newDisabled= localStorage.getItem('disabled')
           newDisabled = JSON.parse(newDisabled)
          
           
            if(newDisabled === true){
            
             euro[i].disabled = true
            }
            
            
            
            
            

            
         }  
         
         
    })
}

         


  function onLoadCartNumbers(){
    let productNumbers = localStorage.getItem('cartNumbers')
    if(productNumbers){
        lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers}</div>`
    }

}

  function cartNumbers(product){
    console.log('the product clicked is', product)
    let productNumbers = localStorage.getItem('cartNumbers')
    productNumbers = parseInt(productNumbers)
    if(productNumbers){
        localStorage.setItem('cartNumbers', productNumbers + 1)
        lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers +1}</div>`
    }
    else {
        localStorage.setItem('cartNumbers', 1 )
        lang1.innerHTML = `<div id="cartNr">${cartNr = 1}</div>`
    }
   
    setItems(product)
    
  }

  
  

  function setItems(product){
    let cartItems = localStorage.getItem('productsInCart')
    cartItems = JSON.parse(cartItems)
    console.log(cartItems) //funkar
    if(cartItems != null){
        if(cartItems[product.id] == undefined){
            cartItems = {
                ...cartItems,
                [product.id]: product
            }
            console.log(cartItems)
        }else {
        cartItems[product.id].inCart += 1
        
        cartItems[product.id].lager = 10 - cartItems[product.id].inCart
        //product.lager--
        product.inCart++
        
        console.log(cartItems) //funkar
        
        }
    }
    else{
        product.inCart = 1
        product.lager = 9
        cartItems = {
            [product.id]: product
    }
    console.log(cartItems)//funkar
  
    }
    
    localStorage.setItem('productsInCart',JSON.stringify(cartItems))
    console.log(localStorage.getItem('productsInCart'))
}

  function totalCost(product){
    let cartCost = localStorage.getItem('totalCost')
    if(cartCost != null){
        cartCost = parseInt(cartCost)
        localStorage.setItem('totalCost', cartCost + product.pris)
    }
    else{
        localStorage.setItem('totalCost', product.pris)
    }
    
  }

  async function patchPost(obj){
    const baseURL = `https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/`
    const url = baseURL + `Products.json`
        const init = {
            method: 'PUT',
            body: JSON.stringify(obj),
            headers: {
                "Content-type": "application/json; charset=UTF-8",
            }
        };
    
        const response = await fetch(url, init)
        const data = await response.json()
        console.log(data)
        
    }
     let obj = Object.values(products) 
    patchPost(obj)
    console.log(obj)
    localStorage.setItem('obj', obj)

  onLoadCartNumbers()
<div class="grid"  id="container">
      <div class="div-container">
                <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DV1129-300_1.jpg?timestamp=1677759773" alt=""></div>
                <div class="beskrivning"><strong class="text">Sneaker1</strong><br>
                    <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
            </div>
            <div class="div-container">
                <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/AH6789-006_1.jpg" alt=""></div>
                <div class="beskrivning"><strong class="text">Sneaker2</strong><br>
                    <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                <div class="pris"><p class="lager"></p> <button class="euro">Buy: 1500kr</button></div>
            </div>
            <div class="div-container">
                <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DV1129-001_1.jpg?timestamp=1673044814" alt=""></div>
                <div class="beskrivning"><strong class="text">Sneaker3</strong><br>
                    <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                <div class="pris"><p class="lager"></p> <button class="euro">Buy: 1500kr</button></div>
            </div>
            <div class="div-container">
                <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/AH6789-001_1.jpg?timestamp=1609192138" alt=""></div>
                <div class="beskrivning"><strong class="text">Sneaker4</strong><br>
                    <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
            </div>
            <div class="div-container">
                <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DM2361-100_0.jpg?timestamp=1628091117" alt=""></div>
                <div class="beskrivning"><strong class="text">Sneaker5</strong><br>
                    <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
            </div>
            
    </div>

2

Answers


  1. It looks like you need to set the values of products[i].incart to whatever is already in the user’s cart before you run the for loop.

    Also have you got an "and" logical operator in your if statement? products[i].inCart === 10 && products[i].lager === 0

    This statement might be safer:

    products[i].inCart > 9 || products[i].lager < 1

    Login or Signup to reply.
  2. For storing the values of ‘disabled’ for each item, I made it an array.

    That is, for the first time, it will contain ‘false’ for all items.

    Then on subsequent occasions it will get updated with the localStorage values.

    So I have changed this part of your code:

    const euro = document.querySelectorAll('.euro')
    let disabled = [false, false, false, false, false];
    let newDisabled = disabled;
    let newDisabled1 = []; 
    for(let i = 0; i < euro.length; i++ ){
            
            euro[i].addEventListener('click', (e) => {
                e.preventDefault()
                
                cartNumbers(products[i])
                totalCost(products[i])
               
                 if(products[i].inCart > 9 || products[i].lager < 1){
                   disabled[i] = true;
                   localStorage.setItem('disabled', JSON.stringify(disabled) )//Uses JSON.stringify to store disabled as an JSON array. Otherwise it will result in a string.
                    }
                newDisabled = localStorage.getItem('disabled')
                if(newDisabled){//this is to check whether newDisabled is null or not (null in case of absence of disabled in localStorage)
                newDisabled1[i]= JSON.parse(newDisabled)[i];
                if(newDisabled1[i] === true){
                     euro[i].disabled = true
                }
                }
            })
            //following section is to disable the button depending on the local storage value on page load
            newDisabled = localStorage.getItem('disabled')
            if(newDisabled){//this is to check whether newDisabled is null or not (null in case of absence of disabled in localStorage)
                newDisabled1[i]= JSON.parse(newDisabled)[i];
                   
                if(newDisabled1[i] === true){
                     euro[i].disabled = true
                }
                }
        }
    

    I have added comments on the code as explanation.

    So your full code becomes:

    const wrapper = document.querySelector('.grid')
        let lager = 10
        let productsArray= []
        let datavar = ''
    
        async function getProducts(){
          try{
            const baseURL = 'https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/'
            const url = baseURL + 'Products.json'
            const response = await fetch(url)
            let data = await response.json()
            console.log(data)
            productsArray.push(data)
            datavar = Object.keys(data)
            console.log(datavar)
            console.log(productsArray)
            
            
          }catch(error){
            console.log(error)
          }
          
    
          }
    
        getProducts()
    
    
        let cartNr = document.getElementById('cartNr')
        const lang1 = document.querySelector('.lang1')
        cartNr = 1
    
        let products = [
            {
                id: 0,
                namn: 'Sneaker1',
                img: '//shelta.se/pub_images/original/DV1129-300_1.jpg?timestamp=1677759773',
                pris: 1500,
                lager: 10,
                inCart: 0
            },
            {
                id: 1,
                namn: 'Sneaker2',
                img: 'https://shelta.se/pub_images/original/AH6789-006_1.jpg',
                pris: 1500,
                lager: 10,
                inCart: 0
            },
            {
                id: 2,
                namn: 'Sneaker3',
                img: 'https://shelta.se/pub_images/original/DV1129-001_1.jpg?timestamp=1673044814',
                pris: 1500,
                lager: 10,
                inCart: 0
            },
            {
                id: 3,
                namn: 'Sneaker4',
                img: 'https://shelta.se/pub_images/original/AH6789-001_1.jpg?timestamp=1609192138',
                pris: 1500,
                lager: 10,
                inCart: 0
            },
            {
                id: 4,
                namn: 'Sneaker5',
                img: 'https://shelta.se/pub_images/original/DM2361-100_0.jpg?timestamp=1628091117',
                pris: 1500,
                lager: 10,
                inCart: 0
            }
        ]
    
    
    
        const euro = document.querySelectorAll('.euro')
        let disabled = [false, false, false, false, false];
        let newDisabled = disabled;
        let newDisabled1 = []; 
        for(let i = 0; i < euro.length; i++ ){
            
            euro[i].addEventListener('click', (e) => {
                e.preventDefault()
                
                cartNumbers(products[i])
                totalCost(products[i])
               
                 if(products[i].inCart > 9 || products[i].lager < 1){
                   disabled[i] = true;
                   localStorage.setItem('disabled', JSON.stringify(disabled) )//Uses JSON.stringify to store disabled as an JSON array. Otherwise it will result in a string.
                    }
                newDisabled = localStorage.getItem('disabled')
                if(newDisabled){//this is to check whether newDisabled is null or not (null in case of absence of disabled in localStorage)
                newDisabled1[i]= JSON.parse(newDisabled)[i];
                if(newDisabled1[i] === true){
                     euro[i].disabled = true
                }
                }
            })
            //following section is to disable the button depending on the local storage value on page load
            newDisabled = localStorage.getItem('disabled')
            if(newDisabled){//this is to check whether newDisabled is null or not (null in case of absence of disabled in localStorage)
                newDisabled1[i]= JSON.parse(newDisabled)[i];
                   
                if(newDisabled1[i] === true){
                     euro[i].disabled = true
                }
                }
        }
    
                 
    
    
          function onLoadCartNumbers(){
            let productNumbers = localStorage.getItem('cartNumbers')
            if(productNumbers){
                lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers}</div>`
            }
        }
    
          function cartNumbers(product){
            console.log('the product clicked is', product)
            let productNumbers = localStorage.getItem('cartNumbers')
            productNumbers = parseInt(productNumbers)
            if(productNumbers){
                localStorage.setItem('cartNumbers', productNumbers + 1)
                lang1.innerHTML = `<div id="cartNr">${cartNr = productNumbers +1}</div>`
            }
            else {
                localStorage.setItem('cartNumbers', 1 )
                lang1.innerHTML = `<div id="cartNr">${cartNr = 1}</div>`
            }
           
            setItems(product)
            
          }
    
          
          
    
          function setItems(product){
            let cartItems = localStorage.getItem('productsInCart')
            cartItems = JSON.parse(cartItems)
            console.log(cartItems) //funkar
            if(cartItems != null){
                if(cartItems[product.id] == undefined){
                    cartItems = {
                        ...cartItems,
                        [product.id]: product
                    }
                    console.log(cartItems)
                }else {
                cartItems[product.id].inCart += 1
                
                cartItems[product.id].lager = 10 - cartItems[product.id].inCart
                //product.lager--
                product.inCart++
                
                console.log(cartItems) //funkar
                
                }
            }
            else{
                product.inCart = 1
                product.lager = 9
                cartItems = {
                    [product.id]: product
            }
            console.log(cartItems)//funkar
          
            }
            
            localStorage.setItem('productsInCart',JSON.stringify(cartItems))
            console.log(localStorage.getItem('productsInCart'))
        }
    
          function totalCost(product){
            let cartCost = localStorage.getItem('totalCost')
            if(cartCost != null){
                cartCost = parseInt(cartCost)
                localStorage.setItem('totalCost', cartCost + product.pris)
            }
            else{
                localStorage.setItem('totalCost', product.pris)
            }
            
          }
    
          async function patchPost(obj){
            const baseURL = `https://webstore-22fa4-default-rtdb.europe-west1.firebasedatabase.app/`
            const url = baseURL + `Products.json`
                const init = {
                    method: 'PUT',
                    body: JSON.stringify(obj),
                    headers: {
                        "Content-type": "application/json; charset=UTF-8",
                    }
                };
            
                const response = await fetch(url, init)
                const data = await response.json()
                console.log(data)
                
            }
             let obj = Object.values(products) 
            patchPost(obj)
            console.log(obj)
            localStorage.setItem('obj', obj)
    
          onLoadCartNumbers()
        <div class="grid"  id="container">
              <div class="div-container">
                        <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DV1129-300_1.jpg?timestamp=1677759773" alt=""></div>
                        <div class="beskrivning"><strong class="text">Sneaker1</strong><br>
                            <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                        <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
                    </div>
                    <div class="div-container">
                        <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/AH6789-006_1.jpg" alt=""></div>
                        <div class="beskrivning"><strong class="text">Sneaker2</strong><br>
                            <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                        <div class="pris"><p class="lager"></p> <button class="euro">Buy: 1500kr</button></div>
                    </div>
                    <div class="div-container">
                        <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DV1129-001_1.jpg?timestamp=1673044814" alt=""></div>
                        <div class="beskrivning"><strong class="text">Sneaker3</strong><br>
                            <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                        <div class="pris"><p class="lager"></p> <button class="euro">Buy: 1500kr</button></div>
                    </div>
                    <div class="div-container">
                        <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/AH6789-001_1.jpg?timestamp=1609192138" alt=""></div>
                        <div class="beskrivning"><strong class="text">Sneaker4</strong><br>
                            <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                        <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
                    </div>
                    <div class="div-container">
                        <div class="image"><img class="skor-img" src="https://shelta.se/pub_images/original/DM2361-100_0.jpg?timestamp=1628091117" alt=""></div>
                        <div class="beskrivning"><strong class="text">Sneaker5</strong><br>
                            <br><p class="text2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum quas quasi praesentium voluptates minima deleniti enim sint quidem expedita sed ut officiis hic dolore dolor quaerat atque earum tenetur necessitatibus, maiores odit illo molestias voluptatibus adipisci quos? Vero necessitatibus tempora inventore, accusamus illo, maiores quisquam quo odit nesciunt qui nisi hic est non aliquid ex numquam earum aperiam? Recusandae excepturi eligendi nemo magni praesentium assumenda, placeat rem numquam illo provident earum officia eveniet tempora commodi laborum molestias animi expedita nihil sint explicabo quos modi at. Odio vel a voluptas explicabo pariatur.</p></div>
                        <div class="pris"><p class="lager"></p>  <button class="euro">Buy: 1500kr</button></div>
                    </div>
                    
            </div>
    <div class="lang1"></div>

    localStorage won’t work on snippet so please try locally.

    For more explanation why I used JSON.stringify, please see this question and its answers.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search