Como tornar a tabela HTML editável?

gostaria de tornar algumas células da tabela html editáveis, basta fazer duplo-click numa célula, introduzir algum texto e as alterações podem ser enviadas para o servidor. Não quero usar ferramentas como a grelha de dados do dojo. Porque ele fornece algumas outras características. Pode fornecer-me alguns excertos de código ou conselhos sobre como implementá-lo?

Author: Michał Perłakowski, 2011-05-16

10 answers

Pode usar o atributo contenteditable nas células, linhas ou tabela em questão.

Actualizado para a compatibilidade IE8

<table>
<tr><td><div contenteditable>I'm editable</div></td><td><div contenteditable>I'm also editable</div></td></tr>
<tr><td>I'm not editable</td></tr>
</table>

Apenas note que se tornar a tabela editável, pelo menos no Mozilla, poderá apagar linhas, etc.

Você também precisa verificar se os navegadores do seu público-alvo suportaram este atributo.

Quanto à escuta das alterações (para que possa enviar para o servidor), veja os eventos de alteração contentáveis

 95
Author: Brett Zamir, 2017-05-23 12:02:23

O HTML5 suporta o contentável,

<table border="3">
<thead>
<tr>Heading 1</tr>
<tr>Heading 2</tr>
</thead>
<tbody>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
<tr>
<td contenteditable='true'></td>
<td contenteditable='true'></td>
</tr>
</tbody>
</table>
 36
Author: vardhan, 2014-03-18 04:25:37
Tenho três abordagens., Aqui pode utilizar <input> ou <textarea> de acordo com as suas necessidades.

1. Usar a entrada em <td>.

Usando <input> o elemento em todos <td>,

<tr><td><input type="text"></td>....</tr>
Também podes querer redimensionar a entrada para o tamanho do td. ex.,
input { width:100%; height:100%; }

2. Usar o atributo contenteditable='true'. (HTML5)

Mas se quiser usar contenteditable='true' também pode querer guardar os valores apropriados para a base de dados. você pode conseguir isso com Forum.

Você pode anexar Teclados keyup, keydown, keypress etc para o <td>. Também é bom usar algum atraso () com esses eventos quando o usuário continuamente escreve, o evento ajax não vai disparar com cada tecla de usuário pressiona. por exemplo,

$('table td').keyup(function() {
  clearTimeout($.data(this, 'timer'));
  var wait = setTimeout(saveData, 500); // delay after user types
  $(this).data('timer', wait);
});
function saveData() {
  // ... ajax ...
}

3. Adicionar <input> a <td> quando for clicado.

Adicione o elemento de entrada em td quando o <td> for clicado, substitua o seu valor de acordo com o valor do td. Quando a entrada é blured, alterar o valor do td com o o valor da entrada. Tudo isto com javascript.

 15
Author: Bhavesh Gangani, 2017-05-23 12:34:17

Pode usar x-editable https://vitalets.github.io/x-editable/ a sua fantástica biblioteca de bootstrap

 4
Author: Ahmad Halah, 2016-12-20 13:43:20

Se usar o Jquery, este 'plugin' ajudá-lo-á é simples, mas é bom.

Https://github.com/samuelsantosdev/TableEdit

 3
Author: user3333866, 2014-02-20 17:18:24
Tenta este código.
$(function () {
 $("td").dblclick(function () {
    var OriginalContent = $(this).text();

    $(this).addClass("cellEditing");
    $(this).html("<input type="text" value="&quot; + OriginalContent + &quot;" />");
    $(this).children().first().focus();

    $(this).children().first().keypress(function (e) {
        if (e.which == 13) {
            var newContent = $(this).val();
            $(this).parent().text(newContent);
            $(this).parent().removeClass("cellEditing");
        }
    });

 $(this).children().first().blur(function(){
    $(this).parent().text(OriginalContent);
    $(this).parent().removeClass("cellEditing");
 });
 });
});

Você também pode visitar este link para mais detalhes:

 3
Author: user3751006, 2014-06-18 05:58:23
Este é um exemplo único e executável.
 <html>
            <head>
                    <script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script> <!-- jQuery source -->
            </head>
            <body>
                    <table align="center">
                            <tr> <td>id</td> <td>name</td> </tr>
                            <tr> <td>001</td> <td>dog</td> </tr>
                            <tr> <td>002</td> <td>cat</td> </tr>
                            <tr> <td>003</td> <td>pig</td> </tr>
                    </table>
                    <script>
    $(function(){
            $("td").click(function(event){
                    if($(this).children("input").length > 0)
                            return false;
                    var tdObj = $(this);
                    var preText = tdObj.html();
                    var inputObj = $("<input type='text' />");
                    tdObj.html("");
                    inputObj.width(tdObj.width())
                            .height(tdObj.height())
                            .css({border:"0px",fontSize:"17px"})
                            .val(preText)
                            .appendTo(tdObj)
                            .trigger("focus")
                            .trigger("select");
                    inputObj.keyup(function(event){
                            if(13 == event.which) { // press ENTER-key
                                    var text = $(this).val();
                                    tdObj.html(text);
                            }
                            else if(27 == event.which) {  // press ESC-key
                                    tdObj.html(preText);
                            }
                  });
                    inputObj.click(function(){
                            return false;
                    });
            });
    });
                    </script>
            </body>
    </html>
 3
Author: ACE Arthur, 2016-10-08 14:53:33

Basta inserir <input> elemento em <td> dinamicamente, ao clique celular. Apenas HTML e Javascript simples. Não é necessário contentEditable , jquery, HTML5

Https://Jsfiddle.net/gsivanov/38tLqobw/2/

 2
Author: gsivanov, 2017-09-19 14:43:15
Isto é tão directo para a frente., esta é a minha amostra de HTML, jQuery.. e funciona como um encanto, eu construo todo o código usando uma amostra de dados on-line da json. saúde.

>

<table id="myTable"></table>

>

<script>
        var url = 'http://jsonplaceholder.typicode.com/posts';
        var currentEditedIndex = -1;
        $(document).ready(function () {
            $.getJSON(url,
            function (json) {
                var tr;
                tr = $('<tr/>');
                tr.append("<td>ID</td>");
                tr.append("<td>userId</td>");
                tr.append("<td>title</td>");
                tr.append("<td>body</td>");
                tr.append("<td>edit</td>");
                $('#myTable').append(tr);

                for (var i = 0; i < json.length; i++) {
                    tr = $('<tr/>');
                    tr.append("<td>" + json[i].id + "</td>");
                    tr.append("<td>" + json[i].userId + "</td>");
                    tr.append("<td>" + json[i].title + "</td>");
                    tr.append("<td>" + json[i].body + "</td>");
                    tr.append("<td><input type='button' value='edit' id='edit' onclick='myfunc(" + i + ")' /></td>");
                    $('#myTable').append(tr);
                }
            });


        });


        function myfunc(rowindex) {

            rowindex++;
            console.log(currentEditedIndex)
            if (currentEditedIndex != -1) {  //not first time to click
                cancelClick(rowindex)
            }
            else {
                cancelClick(currentEditedIndex)
            }

            currentEditedIndex = rowindex; //update the global variable to current edit location

            //get cells values
            var cell1 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").text());
            var cell2 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").text());
            var cell3 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").text());
            var cell4 = ($("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").text());

            //remove text from previous click


            //add a cancel button
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").append(" <input type='button' onclick='cancelClick("+rowindex+")' id='cancelBtn' value='Cancel'  />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(4)").css("width", "200");

            //make it a text box
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(0)").html(" <input type='text' id='mycustomid' value='" + cell1 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(1)").html(" <input type='text' id='mycustomuserId' value='" + cell2 + "' style='width:30px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(2)").html(" <input type='text' id='mycustomtitle' value='" + cell3 + "' style='width:130px' />");
            $("#myTable tr:eq(" + (rowindex) + ") td:eq(3)").html(" <input type='text' id='mycustomedit' value='" + cell4 + "' style='width:400px' />");

        }

        //on cancel, remove the controls and remove the cancel btn
        function cancelClick(indx)
        {

            //console.log('edit is at row>> rowindex:' + currentEditedIndex);
            indx = currentEditedIndex;

            var cell1 = ($("#myTable #mycustomid").val());
            var cell2 = ($("#myTable #mycustomuserId").val());
            var cell3 = ($("#myTable #mycustomtitle").val());
            var cell4 = ($("#myTable #mycustomedit").val()); 

            $("#myTable tr:eq(" + (indx) + ") td:eq(0)").html(cell1);
            $("#myTable tr:eq(" + (indx) + ") td:eq(1)").html(cell2);
            $("#myTable tr:eq(" + (indx) + ") td:eq(2)").html(cell3);
            $("#myTable tr:eq(" + (indx) + ") td:eq(3)").html(cell4);
            $("#myTable tr:eq(" + (indx) + ") td:eq(4)").find('#cancelBtn').remove();
        }



    </script>
 0
Author: Mahmoud Sayed, 2016-07-10 06:58:39
Este é o ponto essencial, embora não precises de tornar o código tão confuso. Em vez disso, você poderia apenas iterar através de todo o <td> e adicionar o <input> com os atributos e finalmente colocar os valores.

function edit(el) {
  el.childNodes[0].removeAttribute("disabled");
  el.childNodes[0].focus();
  window.getSelection().removeAllRanges();
}
function disable(el) {
  el.setAttribute("disabled","");
}
<table border>
<tr>
<td ondblclick="edit(this)"><input value="cell1" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="cell2" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="cell3" disabled onblur="disable(this)"></td>
<td ondblclick="edit(this)"><input value="so forth..." disabled onblur="disable(this)">
</td>
</tr>
</table>
 0
Author: awesomeguy, 2018-05-22 01:12:39