开发者

Javascript function to append table with cells containing input field and value

开发者 https://www.devze.com 2023-02-16 01:45 出处:网络
I created a working function that appends a table with cells/rows and then populates those cells with data from an array. The problem is now I need to change it so that the generated cells contain an

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

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

at one point I tried changing to cell.innerHTML = "<input type='text' size='1'>"+ subset[i++] +"</input>" but it just put the data outside of the input text area.

subset[i++] creates the correct output but I cant seem to get it inside a field value.

Here is the function before I edited it for an 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++) {
开发者_StackOverflow社区            var cell = row.insertCell(c);
            cell.appendChild(document.createTextNode(subset[i++]));
        }
    }
}


Instead of doing:

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

Try to do this:

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

Using the value property of the input, this way it should work.


You were on the right track, you need to add the text to the input value like:

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

and your subset needs to be populated with some values.


Use this:

 value=''+subset[i++]

instead of

value='subset[i++]'

So your new function should read like :

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++] />"
        }
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消