Dub Kelly Dub Kelly - 1 year ago 45
Javascript Question

storing local variable then re-running function?

So I'm making an app that, in a nut shell, takes dimensions from the user and spits out the surface area but it's quickly becoming really repetitive.

function calc() {

var dim1main = +document.getElementById("dim1main").value || 0;
var dim2main = +document.getElementById("dim2main").value || 0;
var mainSurA = dim1main * dim2main;

var dim1mainD1 = +document.getElementById("dim1mainD1").value || 0;
var dim2mainD1 = +document.getElementById("dim2mainD1").value || 0;
var mainD1SurA = dim1mainD1 * dim2mainD1;

// ...

var dim1mainD6 = ...

// ...

var totalSurA = mainSurA + mainD1SurA ... + mainD6SurA;

So the idea was to have hundreds of text inputs hidden until the user wanted them and everything that was left empty would run through as zero, therefor not messing with the total. I think I'm safe in assuming this is horrible javascript.

I've been looking for a way to run a function multiple times and store each local variable somewhere for later use. I've played with arrays by deleting the input values onClick but each time I run the function with .push it replaces the first value with the second. I've read about localStorage but I'm not sure that's what I'm looking for. Any suggestions? Sorry if this is too vague.

I have read about storing data in objects as well as global variables but I've heard that gets messy.

Answer Source

One way you can do this is instead of hiding many elements you can dynamically create new input elements when needed. You can give your elements a specific class which you can use to get it via a HTMLCollection and compute the total dimension.

For example:

document.getElementById('add').onclick = function() 
  var container = document.getElementById('container');
  var subContainer = document.createElement("div");
  var dim1 = document.createElement("input");
  var dim2 = document.createElement("input");
  dim1.className = "dim1";
  dim2.className = "dim2";
  dim1.value = dim2.value = 0;
  subContainer.className = "sub-container";

document.getElementById('calc').onclick = function()
  var arrayDim1 = document.getElementsByClassName('dim1');
  var arrayDim2 = document.getElementsByClassName('dim2');
  var totalSurA = 0;
  for (var i = 0; i < arrayDim1.length; i++) {
      totalSurA += +arrayDim1[i].value * +arrayDim2[i].value;
<div id="container"></div>
<button id="add">Add Dimension</button>
<button id="calc">Calculate</button>

For storing past page sessions you can use localStorage as you said. I would in JavaScript as a 2D array of each row item (or you can use an array of objects with a property for dim1/dim2), like so:

    [dim1_0, dim2_0],
    [dim1_1, dim2_1],

Although before saving it to local storage you need it in a text format, which you can convert it to using JSON.stringify()