Javascript function to add a table with cells containing an input field and value

I created a working function that adds a table with cells / rows, and then populates these cells with data from an array. The problem now is that I need to change it so that the generated cells contain a field input, where value=is the data in the array.

Here is an example of the closest I was able to come with: http://jsfiddle.net/JEAkX/3/

at some point I tried to switch to cell.innerHTML = "<input type='text' size='1'>"+ subset[i++] +"</input>", but it just placed the data outside the text input area.

subset[i++] creates the correct output, but I cannot get it inside the field value.

Here is the function up . I edited it for the input field:

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 4; r++) {
        var row = tbody.insertRow(r);
        for (var c = 0; c < 4; c++) {
            var cell = row.insertCell(c);
            cell.appendChild(document.createTextNode(subset[i++]));
        }
    }
}
+3
3

:

cell.innerHTML = "<input type='text' size='1'>"+ subset[i++] +"</input>"

:

cell.innerHTML = "<input type='text' size='1' value='" + subset[i++] + "'/>"

, .

+1

, , :

cell.innerHTML = "<input type='text' size='1' value='" + subset[i++] + "' />";

.

+1

Use this:

 value=''+subset[i++]

instead

value='subset[i++]'

So your new function should look like this:

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 4; r++) {
        var row = tbody.insertRow(r);
        for (var c = 0; c < 4; c++) {
            var cell = row.insertCell(c);
            cell.innerHTML = "<input type='text' size='1' value=''+subset[i++] />"
        }
    }
}
+1
source

All Articles