skip to Main Content

Code looks something like this

let sectionWithLimitItems = [];

function addItems(productId) {
     sectionWithLimitItems.push(productId)
}

<button onclick='appendItems({{ productId }})'>Click Me</button>

Working with liquid, Shopify’s theme template language, but not sure if that would create complications.
If I log the array each time the function is called, it is empty after at the start of the function and can see the id gets added but the array is empty again on the next button click. Any ideas?

— Edit – sorry for the mistake everyone! I did have arr.push in my code, not append. Wasn’t thinking correctly when I made the post. Still having the same issue with sectionWithLimitItems.push(productId)

3

Answers


  1. In javascript you don’t use Array.append(), you should use Array.push() (MDN Reference) instead.

    Login or Signup to reply.
  2. I think you might be looking for Array.push()

    const sectionWithLimitItems = [];
    
    function appendItems(productId) {
        sectionWithLimitItems.push(productId)
    }
    
    <button onclick='appendItems({{ productId }})'>Click Me</button>
    
    Login or Signup to reply.
  3. For Arrays data structures in Javascript you use the push() method to add at the end of the Array. For a more detailed explanation check out https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

    let sectionWithLimitItems = [];
    
    function appendItems(arr,item) {
      arr.push(item)
    }
    
    console.log(sectionWithLimitItems)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search