0

I'm trying to build a table that the user can hit "new line" to create a new row of the table. I do this by foo.push(document.createElement("INPUT"));

function newLine() {
  sArr.push(document.createElement("INPUT"));
  sArr[sArr.length-1].setAttribute("type", "text");
  document.body.appendChild(sArr[sArr.length-1]);

  gArr.push(document.createElement("INPUT"));
  gArr[gArr.length-1].setAttribute("type", "text");
  document.body.appendChild(gArr[gArr.length-1]);

  tArr.push(document.createElement("INPUT"));
  tArr[tArr.length-1].setAttribute("type", "text");
  document.body.appendChild(tArr[tArr.length-1]);
  //alert(sArr.length+", "+gArr.length+", "+tArr.length);
  var x = document.createElement("br");
  document.body.appendChild(x);
}

function calc(){
  var temp = 0;
  var total = 0;

  for(i = 0; i<sArr.length; i++){
    total = total + calc2(i);
  }

  var o = document.getElementById("output");
  o.value = total;
}

function calc2(i){
  alert(i);
  var s = document.getElementById(sArr[i]);
  var g = document.getElementById(gArr[i]);
  var t = document.getElementById(tArr[i]);
  var VO2walkmin = 3.28; 
  var VO2rest = 3.05; 
  var C1 = 0.32;
  var C2 = 0.19;
  var C3 = 2.66;
  var Cdecline = 0.73;
  var s2 = s.value;
  var g2 = g.value;
  var t2 = t.value;
  var negGrade = g.value;

  if(g2 < 0){g2 = 0};

  VO2move = ((C1 * g2)+VO2walkmin)+((1+(C2*g2))*(C3*(s2^2)));

  VO2inc = VO2rest+(t2*VO2move);

  VO2dec = VO2rest+(Cdecline*(t2*VO2move))

  //var o = document.getElementById("output");

  return VO2inc;
}

When run, I get the error:

Uncaught TypeError: Cannot read property 'value' of null

from line 66. Specifically, this line:

var s2 = s.value;

I'm struggling to find my mistake here... and all help is appreciated.

1
  • It means the line above with document.getElementById(sArr[i]) didn't find any element with that ID in your document, because sArr[i] is an object, not a string. Assign an attribute "id" if you want to get elements by id. Commented Aug 8, 2019 at 0:21

2 Answers 2

2

You create a new element, but it has no ID. And so you can't fetch it by ID. The result of document.getElementById(sArr[i]) will be null.

Check this answer to see how ID can be assigned to a newly created element:

Create element with ID

Sign up to request clarification or add additional context in comments.

1 Comment

Why add an ID when you can just access the element directly from the arrays?
0

There's no need to use document.getElementById. sArr[i] is the input element itself, not its ID, so you can just read its value directly.

var s = sArr[i];
var g = gArr[i];
var t = tArr[i];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.