Search code examples
javascriptcountergoogle-app-maker

How to increment counter value inside an onClick event?


I'm quite new to Google App Maker and programming in general, I'm making an app where when a "+" button is clicked (onClick event) fields are added (kinda like a new row in a table with every click). I'm trying to make a counter to keep track of how many "rows" are being created. The thing is that since in App Maker all the code apparently has to be made inside the onClick event, i can't set a global variable and every time the button is clicked the counter restarts, therefore always being 1.

I tried with localStorage but i don't exactly know how to make it work, since it still will always save the same value. How can i fix this?

  var count = 0;
  count = count +1;
  localStorage.setItem('counter', JSON.stringify(parseFloat(count)));

  textArea.className = 'app-TextArea';
  textArea.style.margin = '8px';
  textArea.setAttribute("placeholder", "Follow up # " + localStorage.getItem('counter');

  widget.root.descendants.Panel1.getElement().appendChild(textArea);

Solution

  • You should get data from localStorage first, then increment it and finally set the new value the localStorage.

    var count = parseInt(localStorage('counter')) || 0; // Get value from localStorage 
    count = count + 1;
    localStorage.setItem('counter', count); // Set new value to localStorage
    
    textArea.className = 'app-TextArea';
    textArea.style.margin = '8px';
    textArea.setAttribute("placeholder", "Follow up # " + count); // Use new value
    
    widget.root.descendants.Panel1.getElement().appendChild(textArea);