3

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++) {
            var cell = row.insertCell(c);
            cell.appendChild(document.createTextNode(subset[i++]));
        }
    }
}
2
  • All these answers here work, thanks guys! Giving it @JeanK for being first. Commented Mar 10, 2011 at 0:09
  • +1 for using/introducing jsfiddle (for people unfamiliar with it. e.g. myself) Commented Mar 10, 2011 at 0:22

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer! I think I tried this once but must have messed up a " somewhere and not double checked when it didn't work.
1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.