Input Text in a dynamic javascript table

4146 views javascript
-1

i try to generate a text field in a table: The table gets bigger with the input of the user that's why I cant just write the input syntax in the html document, because the cell isn´t generated from the beginning.

function tableAdd() {

var table = document.getElementById("table");
var titel = document.getElementById("Titel").value;
var description = document.getElementById("Description").value; 




var row = table.insertRow(); 


var projectCell=row.insertCell(0);
projectCell.innerHTML = titel;


// down here is the problem

var x =row.insertCell(1);
x.innerHTML =  document.createElement("INPUT")
x.innerHTML.setAttribute("type", "text");

}

answered question

2 Answers

12

You are trying to assign a reference of HTMLInputElement which is returned from the call to document.createElement("input"); to the non-existent innerHTML property of a HTMLTableRowElement reference, returned by insertCell(1);.

Instead you can assign any text value to the value attribute of the HTMLInputElement and append the dynamic input to the newly created cell.

function tableAdd() {
   var table = document.getElementById("table");
   var titel = document.getElementById("Titel").value;
   var description = document.getElementById("Description").value; 
   var row = table.insertRow(); 
   var projectCell=row.insertCell(0);
   projectCell.innerHTML = titel;
   // down here is the problem
   var x =row.insertCell(1);
   var input = document.createElement("input");
   input.type = "text";
   input.value= description
   x.appendChild(input);
 }
 tableAdd();
<body>
<input type="text" id="Titel" value="test"/>
<input type="text" id="Description" value="test"/>
<table id="table">
</table>
<button onclick="tableAdd()">add</button>
</body>

Here is the reference documentation:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

posted this
12

The problem is that x.innerHTML is a string, not a html element. You need to set attribute on html element, not string. You can do like this:

var x =row.insertCell(1);
var y = document.createElement("INPUT");
y.setAttribute("type", "text");
x.appendChild(y);

posted this

Have an answer?

JD

Please login first before posting an answer.