I am using JavaScript to grab the value of an input, however, the input is coming back as undefined. I originally put the row in using insertrow and a variable. The row uses a variable as its value because each row is different. Later I call the add section to try and add up all of the numbers in a given column. However, when I call the function and the alert comes back it simply says undefined yet in the actual table on the page the value is there. Why is the value coming back as undefined?
var myHtmlContent = "<tr><td>" + dwgno + "</td><td>"
+ desc + "</td><td>"
+ prof + "</td><td>"
+ piec + "</td><td>"
+ len + "</td><td>"
+ ibft + "</td><td>"
+ obs + "</td><td><input type='number' value=" + bud + "></input></td>" +
"<td><input type='number' value=" + mscmat + "></input></td>" +
"<td><input type='number' value=" + galfin + "></input></td>" +
"<td><input type='number' value=" + fab3 + "></input></td>" +
"<td><input type='number' value=" + ins3 + "></input></td>" +
"<td><input type='number' value=" + ins4 + "></input></td>" +
"</td></tr>"
var tableRef = document.getElementById('myTablesecond').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
// add function:
var table = document.getElementById("myTablesecond");
for (var i = 1, row; row = table.rows[i]; i++) {
alert(row.cells[7].value);
total+=parseFloat(row.cells[7].innerhtml) || 0;
}
2
Answers
<input>
elements havevalue
s,<td>
elements do not.row.cells
is a collection of the latter.You might be looking for
row.cells[7].children[0].value
Nothing has an
innerhtml
. The property isinnerHTML
.Your approach is really not right here. There is no reason to write all that HTML as strings to be concatenated with variables. Instead, hard code the HTML you know you’ll need and just supply content to the elements as needed. In many cases, this will allow you to avoid using
innerHTML
(notinnerhtml
) as.innerHTML
has security and performance implications and should be avoided when possible.Keep in mind that
input
elements do not get closing tags and that non-form elements don’t have avalue
, they havetextContent
.Lastly, while I have shown my example using tables (as you have shown in your question), be aware that you should not be using tables for layout purposes (use CSS for that). Tables are only for displaying tabular data.