简体   繁体   English

没有编辑器插件的数据表内联编辑

[英]Datatable inline editing without editor plugin

I was using 'editor' plugin for data table and following was the code:我正在为数据表使用“编辑器”插件,以下是代码:

Data table editor defined as:数据表编辑器定义为:

        editor = new $.fn.dataTable.Editor( {
        ajax: '/contact/' + Contact.id,
        table: "#contact-datatable",
        fields: [ {
                    name: "id",
                  }, {
                    name: "category",
                    type: "check",
                    options: [
                              { label: 'Science', value: "Science" },
                              { label: 'Maths', value: 'Maths' },
                              { label: 'Economics', value: 'Economics' },
                             ]
                 }
                    ................
              ]
    });

..... .....

$('#contact-datatable').on( 'click', 'tbody td:not(:first-child)', function (e) {
                editor.inline( this, { submitOnBlur: true } );
            } );

Attaching the page with this: When we click on Category, it shows a dropdown for editing (using editor plugin).用这个附加页面:当我们点击类别时,它会显示一个用于编辑的下拉列表(使用编辑器插件)。

But the problem is datatables' editor plugin is not opensource and my project doesn't allow a payable plugin at all.但问题是数据表的编辑器插件不是开源的,我的项目根本不允许付费插件。

Can anyone please help me for inline editing in datatables with out 'editor' plugin?任何人都可以帮助我在没有“编辑器”插件的情况下在数据表中进行内联编辑吗?

Following is the code I wrote without editor :以下是我在没有编辑器的情况下编写的代码:

Contact.dataTable = $('#contact-datatable').dataTable( {
        "ajax": {
                "url" : '/Contact/list/' + Contact.id,
                "dataSrc": function(check) {
                   check.id = Contact.id;
                   return json.check;
                  },
                },
            "responsive": true,
            "order": [],
            "columns": [
                { "data": "id"},
                { "data": "category" },
                { "data": "course" },
                ]
        } );

Category and Course will be a dropdown - and this has to be edit inline.类别和课程将是一个下拉列表 - 这必须是内联编辑。 Below attached a page example.下面附上一个页面示例。

I need 'Category' as an inline editor dropdown and then there will be a button to save我需要“类别”作为内联编辑器下拉菜单,然后会有一个按钮来保存在此处输入图片说明

在此处输入图片说明

Datatables rock! 数据表摇滚! And SpryMedia let us play with it for free! SpryMedia让我们免费玩它! I'm not 100% sure I've used the Editor Plugin despite buying it but I am pleased that I've contributed to its development in some way. 我不是100%肯定我已经使用了编辑器插件尽管购买它但我很高兴我以某种方式为其开发做出了贡献。 One of the main reasons I've not used the plugin is because I was too skint to afford it for a while so wrote my own versions and that's really not that difficult. 我没有使用过这个插件的主要原因之一是因为我太过于无法承受它一段时间所以写了我自己的版本,这真的不那么难。 The steps are quite simple: 步骤很简单:

  • Detect click on row (you've already done this) 检测点击行(你已经完成了这个)
  • Get the data from the row (not at all hard) 从行中获取数据(完全没有硬)
  • Populate a form with that data (probably within a modal) 使用该数据填充表单(可能在模态内)
  • Update the server with the new values once the form is submitted 提交表单后,使用新值更新服务器
  • Update the row once the server has been updated 更新服务器后更新行

The plugin makes all that easy and allows you to figure out the backend as well. 该插件使这一切变得简单,并允许您找出后端。 The steps above aren't all that difficult but I've not come across something that does it all for you except for the Editor Plugin. 上面的步骤并不是那么困难,但除了编辑器插件之外,我没有遇到任何事情。 Work through the steps and you'll get there. 完成这些步骤,你就会到达那里。

I wrote my own code for editing inline and made it such that you can edit complete row and define the columns you want to be editable by user. 我编写了自己的内联编辑代码,使得您可以编辑完整的行并定义您希望用户可编辑的列。

here : https://github.com/sinhashubh/datatable-examples 这里: https//github.com/sinhashubh/datatable-examples

Steps to do this: 执行此操作的步骤:

  1. Handle click even on the clicked row/cell. 即使在单击的行/单元格上也可以单击。

      $("#dtexample tbody").on('click', 'tr td', function (e) { RoweditMode($(this).parent()); }); function RoweditMode(rowid) { var prevRow; var rowIndexVlaue = parseInt(rowid.attr("indexv")); if (editIndexTable == -1) { saveRowIntoArray(rowid); rowid.attr("editState", "editState"); editIndexTable = rowid.rowIndex; setEditStateValue(rowid, rowIndexVlaue + 2); } else { prevRow = $("[editState=editState]"); prevRow.attr("editState", ""); rowid.attr("editState", "editState"); editIndexTable = rowIndexVlaue; saveArrayIntoRow(prevRow); saveRowIntoArray(rowid); setEditStateValue(rowid, rowIndexVlaue + 2); } } function saveRowIntoArray(cureentCells) { $.each(ColumnData, function (index, element) { if (element.Editable == true) { var htmlVal = $($(cureentCells).children('.' + element.Name)[0]).html(); EditRowData[element.Name] = htmlVal; } }); } function setEditStateValue(td1, indexRow) { for (var k in EditRowData) { $($(td1).children('.' + k)[0]).html('<input value="' + EditRowData[k] + '" class="userinput" style="width: 99% " />'); } } 
  2. On pressing Enter after inputting anything, bind enter input (You can change it to maybe a save button as you like. 在输入任何内容后按Enter键,输入enter输入(您可以根据需要将其更改为可能的保存按钮。

      $("#dtexample tbody").on('keyup', 'input.userinput', function (e) { if (e.keyCode == 13) { updateRowData(this.parentNode.parentNode); } }); 
  3. Update function to make call to server with parameters. 更新功能以使用参数调用服务器。

      function updateRowData(currentCells) { var table = $("#dtexample").DataTable(); var row = table.row(currentCells); rowid = currentCells.getAttribute('id'); var UpdateRowData = []; $.each(ColumnData, function (index, element) { if (element.Editable==true) { UpdateRowData.push({ 'pname': element.Name , 'pvalue': $($($(currentCells).children('.' + element.Name)).children('input')[0]).val() }); } }); console.log(UpdateRowData); UpdateRowData.push({ 'pname': 'rowid', 'pvalue': rowid }); var parameter = ""; for (i = 0; i < UpdateRowData.length; i++) { if (i == UpdateRowData.length - 1) parameter = parameter + UpdateRowData[i].pname + "=" + UpdateRowData[i].pvalue; else parameter = parameter + UpdateRowData[i].pname + "=" + UpdateRowData[i].pvalue + "&"; } $.ajax({ type: 'POST', url: '/WebService.asmx/UpdateTableData', data: parameter, success: function (data) { var table = $('#dtexample').DataTable(); table.draw('page'); } }); } 

The editor license bit me in the butt, so I'm here to hopefully save yours.编辑器许可证让我很不爽,所以我来这里是为了拯救你的许可证。

Here's how I went about it:这是我的做法:

  1. When creating the table, add the class 'editable' to any element you'd like to edit创建表格时,将“editable”类添加到您要编辑的任何元素

    example = new DataTable('#example', { columns: [ { data: 'domain', name: 'domain' }, { data: 'owner1', name: 'owner1', className: 'editable' }, { data: 'owner2', name: 'owner2', className: 'editable' }, { data: 'description', name: 'description', className: 'editable' }, { data: 'account_state', name: 'account-state' }, ], });
  2. Create mouse events for when you enter/exit a td.为您进入/退出 td 时创建鼠标事件。 I chose to create an input element with mouse hover because I didn't want actual html inputs everywhere我选择用鼠标悬停创建一个输入元素,因为我不希望到处都是实际的 html 输入

    // when the mouse enters a cell, create an editor. $('#example').on('mouseenter', 'td.editable', function (e) { e.preventDefault() // I'm a noob, don't know what this means // I think there is some delay on when the events trigger // so sometimes the cell still contains the input element and this check // prevents accidently creating another input element if (e.target.localName != 'input') { let row = e.target._DT_CellIndex.row let col = e.target._DT_CellIndex.column if (!e.target.children.length) { e.target.innerHTML = `<input id="${row}-${col}" type="text" class="editor" value="${e.target.innerHTML}">` } } }) // when the mouse exits the editor, write the data into the table and redraw $('#example').on('mouseleave', 'td.editable', function (e) { e.preventDefault() if (e.target.localName != 'input') { let row = e.target._DT_CellIndex.row let col = e.target._DT_CellIndex.column data_table.cell(row, col).data(e.target.firstElementChild.value) data_table.draw() // up to you } else { // forces write when there is an event delay let [row, col] = e.target.id.split('-') data_table.cell(Number(row), Number(col)).data(e.target.value) } data_table.draw() })

That's it!就是这样!

My table is at most about 2000 entries (definitely still usable), but I 'm sure there are performance improvements, and I'd love to know them!我的表最多大约有 2000 个条目(绝对仍然可用),但我确信有性能改进,我很想知道它们!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM