如何使HTML表格单元格可编辑?

时间:2022-09-12 08:56:10

I'd like to make some cells of html table editable, simply double click a cell, input some text and the changes can be sent to server. I don't want to use some toolkits like dojo data grid. Because it provides some other features. Would you provide me some code snippet or advices on how to implement it?

我想做一些html表格编辑的单元,只需双击一个单元格,输入一些文本,这些更改就可以发送到服务器。我不想使用dojo数据网格这样的工具包。因为它提供了其他一些特性。你能给我一些代码片段或者如何实现它的建议吗?

10 个解决方案

#1


94  

You can use the contenteditable attribute on the cells, rows, or table in question.

您可以在有问题的单元格、行或表上使用contenteditable属性。

Updated for IE8 compatibility

更新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>

Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.

请注意,如果您使表可编辑,至少在Mozilla中,您可以删除行,等等。

You'd also need to check whether your target audience's browsers supported this attribute.

您还需要检查目标用户的浏览器是否支持此属性。

As far as listening for the changes (so you can send to the server), see contenteditable change events

至于监听更改(以便您可以发送到服务器),请参见contenteditable change事件

#2


35  

HTML5 supports contenteditable,

HTML5支持contenteditable,

<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>

#3


14  

I have three approaches, Here you can use both <input> or <textarea> as per your requirements.

我有三种方法,这里您可以根据您的需求使用 <输入> 或

1. Use Input in <td>.

1。在< td >使用输入。

Using <input> element in all <td>s,

在所有s中使用元素,

<tr><td><input type="text"></td>....</tr>

Also You might want to resize the input to the size of it's td. ex.,

您可能还想将输入的大小调整为td的大小。前女友。

input { width:100%; height:100%; }

2. Use contenteditable='true' attribute. (HTML5)

2。使用contenteditable =“真正的”属性。(HTML5)

But if you want to use contenteditable='true' you might also want to save the appropriate values to the database. you can achieve this with ajax.

但是,如果您想使用contenteditable='true',您可能还需要将适当的值保存到数据库中。您可以使用ajax实现这一点。

You can attach keyhandlers keyup, keydown, keypress etc to the <td>. Also it is good to use some delay() with that events when user continuously types, the ajax event won't fire with every key user press. for example,

可以将keyhandlers keyup、keydown、keypress等附加到。另外,当用户连续输入时,最好使用delay(), ajax事件不会在每个关键用户按下时触发。例如,

$('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. Append <input> to <td> when it is clicked.

3所示。添加 <输入> 到点击时。

Add the input element in td when the <td> is clicked, replace it's value according to the td's value. When the input is blured, change the td's value with the input's value. All this with javascript.

当被单击时,在td中添加输入元素,根据td的值替换它的值。当输入变为蓝色时,用输入的值更改td的值。所有这些都使用javascript。

#4


3  

If you use Jquery, this plugin help you is simple, but is good

如果您使用Jquery,这个插件帮助您简单,但是很好

https://github.com/samuelsantosdev/TableEdit

https://github.com/samuelsantosdev/TableEdit

#5


3  

Try this code.

试试这个代码。

$(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");
 });
 });
});

You can also visit this link for more details :

你亦可浏览此连结了解更多详情:

#6


3  

This is a single and runnable example.

这是一个可运行的示例。

 <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>

#7


3  

You can use x-editable https://vitalets.github.io/x-editable/ its awesome library from bootstrap

您可以使用x-editable https://vitalets.github。io/x-editable/它的自引导库非常棒

#8


2  

Just insert <input> element in <td> dynamically, on cell click. Only simple HTML and Javascript. No need for contentEditable , jquery, HTML5

只需在动态中插入 <输入> 元素,在单元格上单击。只有简单的HTML和Javascript。不需要满足,jquery, HTML5

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

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

#9


0  

this is actually so straight forward, this is my HTML, jQuery sample.. and it works like a charm, I build all the code using an online json data sample. cheers

这是我的HTML jQuery示例。它像一个符咒一样工作,我用一个在线json数据样本来构建所有的代码。干杯

<< HTML >>

< < HTML > >

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

<< jQuery >>

< < jQuery > >

<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>

#10


0  

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

这是最重要的一点,尽管您不需要使代码变得如此混乱。相反,您可以遍历所有的,并添加具有属性的,最后放入值。

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>

#1


94  

You can use the contenteditable attribute on the cells, rows, or table in question.

您可以在有问题的单元格、行或表上使用contenteditable属性。

Updated for IE8 compatibility

更新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>

Just note that if you make the table editable, in Mozilla at least, you can delete rows, etc.

请注意,如果您使表可编辑,至少在Mozilla中,您可以删除行,等等。

You'd also need to check whether your target audience's browsers supported this attribute.

您还需要检查目标用户的浏览器是否支持此属性。

As far as listening for the changes (so you can send to the server), see contenteditable change events

至于监听更改(以便您可以发送到服务器),请参见contenteditable change事件

#2


35  

HTML5 supports contenteditable,

HTML5支持contenteditable,

<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>

#3


14  

I have three approaches, Here you can use both <input> or <textarea> as per your requirements.

我有三种方法,这里您可以根据您的需求使用 <输入> 或

1. Use Input in <td>.

1。在< td >使用输入。

Using <input> element in all <td>s,

在所有s中使用元素,

<tr><td><input type="text"></td>....</tr>

Also You might want to resize the input to the size of it's td. ex.,

您可能还想将输入的大小调整为td的大小。前女友。

input { width:100%; height:100%; }

2. Use contenteditable='true' attribute. (HTML5)

2。使用contenteditable =“真正的”属性。(HTML5)

But if you want to use contenteditable='true' you might also want to save the appropriate values to the database. you can achieve this with ajax.

但是,如果您想使用contenteditable='true',您可能还需要将适当的值保存到数据库中。您可以使用ajax实现这一点。

You can attach keyhandlers keyup, keydown, keypress etc to the <td>. Also it is good to use some delay() with that events when user continuously types, the ajax event won't fire with every key user press. for example,

可以将keyhandlers keyup、keydown、keypress等附加到。另外,当用户连续输入时,最好使用delay(), ajax事件不会在每个关键用户按下时触发。例如,

$('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. Append <input> to <td> when it is clicked.

3所示。添加 <输入> 到点击时。

Add the input element in td when the <td> is clicked, replace it's value according to the td's value. When the input is blured, change the td's value with the input's value. All this with javascript.

当被单击时,在td中添加输入元素,根据td的值替换它的值。当输入变为蓝色时,用输入的值更改td的值。所有这些都使用javascript。

#4


3  

If you use Jquery, this plugin help you is simple, but is good

如果您使用Jquery,这个插件帮助您简单,但是很好

https://github.com/samuelsantosdev/TableEdit

https://github.com/samuelsantosdev/TableEdit

#5


3  

Try this code.

试试这个代码。

$(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");
 });
 });
});

You can also visit this link for more details :

你亦可浏览此连结了解更多详情:

#6


3  

This is a single and runnable example.

这是一个可运行的示例。

 <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>

#7


3  

You can use x-editable https://vitalets.github.io/x-editable/ its awesome library from bootstrap

您可以使用x-editable https://vitalets.github。io/x-editable/它的自引导库非常棒

#8


2  

Just insert <input> element in <td> dynamically, on cell click. Only simple HTML and Javascript. No need for contentEditable , jquery, HTML5

只需在动态中插入 <输入> 元素,在单元格上单击。只有简单的HTML和Javascript。不需要满足,jquery, HTML5

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

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

#9


0  

this is actually so straight forward, this is my HTML, jQuery sample.. and it works like a charm, I build all the code using an online json data sample. cheers

这是我的HTML jQuery示例。它像一个符咒一样工作,我用一个在线json数据样本来构建所有的代码。干杯

<< HTML >>

< < HTML > >

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

<< jQuery >>

< < jQuery > >

<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>

#10


0  

This is the essential point although you don't need to make the code this messy. Instead you could just iterate through all the <td> and add the <input> with the attributes and finally put in the values.

这是最重要的一点,尽管您不需要使代码变得如此混乱。相反,您可以遍历所有的,并添加具有属性的,最后放入值。

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>