Reputation: 515
So my ultimate goal is for the user to input three or more words, and then I must seperate the words, I.E if there are 4 words, I have to build 4 Rows with the word in each, I have been at it for hours and just can't figure out why the insertRow() method wont work, its telling me that "cannot call insertRow() method of undefined"
what I have in the else section of my conditional:
//build table around input
var table=document.getElementById('myTable');
for(i=0; i<2; i++)
{
table.insertRow(i);
table.insertCell(i);}
Upvotes: 0
Views: 313
Reputation: 707158
The first problem I see is that you call .insertRow()
on the table DOM object, but then you need to call .insertRow()
on a row, not on the table. See MDN on insertCell for more details. Here's an example of some working code:
function addWords(e) {
var str = document.getElementById("words").value;
var words = str.split(/[\s,]/);
if (words.length && words[0]) {
//build table around input
var table = document.getElementById('myTable');
for (var i = 0; i < words.length; i++) {
var row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = words[i];
}
}
}
And a working demo: http://jsfiddle.net/jfriend00/3g3Qy/
Upvotes: 1
Reputation: 2287
Put a console.log(table)
after var table=...
. If it prints undefined, the problem is that the script is running too soon and you'll need to move the script to the very bottom of the page, or wait for the DOM to load.
Upvotes: 0
Reputation: 1622
You should call insertCell on a Row object.
var row = table.insertRow();
row.insertCell();
Upvotes: 0