user6121651 user6121651 - 8 months ago 52
Javascript Question

getElementById returns NaN

Consider the following example snippet of my code. I have tried parseInt with no luck. Here, I want javascript to set a number in a cell "PICweight" then retrieve it later and place it in a different cell "totalcabin". You can see here, I want to set the number as 1, but when the code runs, it returns NaN in totalcabin.

<td id="PICweight" type="tel"></td>
window.onchange = function setfields() {

document.getElementById("PICweight").innerHTML = 1;
var PICweight = document.getElementById("PICweight").value;

var totalcabin = document.getElementById("totalcabin");
totalcabin.innerHTML = +PICweight


There is no value property of td elements. When you use .value on normal html elements (non input elements) you end up with undefined. Later, you use + to implicitly cast undefined to a number, which results in NaN and your subsequent observation.

You should be using .textContent instead of value to get the text inside of the td element.

var PICweight = document.getElementById("PICweight").textContent;