Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add rows to table dynamically and make content editable

I need to add rows to a table, I have manually added the header row, and make the content editable by the user.

Currently I have

var table = document.getElementById("tableData");

    var add = 5;

    for (var i = 0; i < add; i++) {

        var row = table.insertRow(0);

        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);

        cell1.innerHTML = "New";
        cell2.innerHTML = "New";
    }

which i have used just to practice adding in rows. I've seen that to make a cell editable you need to put a div inside with "contenteditable". How can I add this into the code that i already have?

Thanks

like image 345
jimminybob Avatar asked Apr 26 '13 09:04

jimminybob


People also ask

How to edit data in JavaScript?

append('<tr><td class="data"></td><td class="data"></td><td class="data"></td><td><button class="save">Save</button><button class="edit">Edit</button> <button class="delete">Delete</button></td></tr>'); }); </script> </body>


2 Answers

There is one thing you should note:

<td> elements (among some others) cannot be set to contenteditable directly in IE: See http://msdn.microsoft.com/en-us/library/ms537837(v=vs.85).aspx

For completeness, there are several ways to do this

var table = document.getElementById("tableData");

    var add = 5;

    for (var i = 0; i < add; i++) {

        var row = table.insertRow(0);

        var cell1 = row.insertCell(0);

        // Method 1 (Restricted in IE)
        cell1.innerHTML = "Method 1";
        cell1.setAttribute('contentEditable', 'true');

        // Method 2 (Restricted in IE)
        cell1.innerHTML = "Method 2";
        cell1.contentEditable = true;

        // Method 3 (All browsers)
        cell1.innerHTML = "<div contenteditable>Method 3</div>";

        // Method 4 (All browsers)
        var div1 = document.createElement('div');
        div1.innerHTML = "Method 4";
        cell1.appendChild(div1);
        div1.contentEditable = true;
    }
like image 120
Terry Young Avatar answered Sep 27 '22 01:09

Terry Young


One way is to assign the div as innerHTML:

cell1.innerHTML = "<div contenteditable='true'>New</div>";
like image 36
Michael Besteck Avatar answered Sep 25 '22 01:09

Michael Besteck