Dynamically edit data in Layui table row

Dynamically edit data in Layui table row

Preface

Today I would like to share with you some dynamic table data operations in the classic front-end framework layui, combined with JQuery to dynamically edit the data in the cell. I hope it can help those in need. Come on, let’s encourage each other!

Style Function Description

Initialization Code

According to the Layui development documentation, we can easily write the following code to load built-in components and dynamically fill in table data:

layui.use(function () {
    let layer = layui.layer,
        element = layui.element,
        table = layui.table,
        form = layui.form;
    //Specify the edit field const field = ['typeName'];
    // Table loading data table.render({
        elem: "#newsTypeTable",
        height: 522,
        url: serverBase + "newsType/all",
        parseData: function (res) {
            return {
                "code": res.code,
                "data": res.data.types,
                "count": res.data.count
            };
        },
        // Enable paging page: true,
        request: {
            pageName: 'offset',
            limitName: 'pageSize'
        },
        toolbar: `
            <div>
                {{# if(checkPermission(1, null)){ }}
                    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="add">
                        <i class="layui-icon layui-icon-addition"></i>
                    </button>
                {{# } }}
                {{# if(checkPermission(3, null)){ }}
                    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="batchDel">
                        <i class="layui-icon layui-icon-subtraction"></i>
                    </button>
                {{# } }}
            </div>
        `,
        defaultToolbar: [],
        cols: [
                [
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', sort: true, align: 'center'},
                    {field: 'typeName', title: 'News Category', align: 'center'},
                    {title: 'Operation', fixed: 'right', width: 200, align: 'center', toolbar: '#myBar'}
                ]
        ],
        text: {
            none: 'Showing loneliness~'
        }
    });
});

illustrate

First, request the backend data and assign the requested data through data parsing. Note: If paging is enabled, the backend needs to pass the total number of displayed items. When the page is opened, the default paging request sent is...?page=1&limit=10. Change the parameter name passed through the request attribute. For example, my paging request is changed to...all?offset=1&pageSize=10.

After opening the toolbar, the default header toolbar on the right will be opened. If you don't need it, you need to set the defaultToolbar attribute value to empty. And when you customize the toobar, the HTML tag element must be placed in the div tag to take effect. This is a rule.

Toobar uses Layui template syntax to verify the current administrator's permissions. If the permissions are not available, they will not be displayed.

Enable the checkbox with {type: 'checkbox', fixed: 'left'} and fix it to the leftmost position in the table.

In the action bar, introduce external custom toolbar by id

<script type="text/html" id="myBar">
    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="edit">
        <i class="layui-icon layui-icon-edit"></i>
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-primary" lay-event="del">
        <i class="layui-icon layui-icon-delete"></i>
    </button>
</script>

Adding event listeners

Listener Toolbar

table.on('toolbar(newsTypeList)', function(obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    // Selected row data let selectedData = checkStatus.data;
    if(obj.event === 'add') {
        // Jump to the news type adding page window.open('addNewsType.html', 'mainFrame');
    }else if(obj.event === 'batchDel') {
        if(selectedData.length > 0) {
            let ids = [];
            selectedData.forEach((targetRow) => {
                ids.push(targetRow.id)
            });
            layer.confirm(`Are you sure you want to delete ID[${ids}]?`, {title: 'Warning', icon: 0},
                function (index) {
                    $.ajax({
                        type: "DELETE",
                        contentType: "application/json;charset=UTF-8",
                        url: serverBase + "newsType/del",
                        data: JSON.stringify(ids),
                        dataType: 'json',
                        success: function (res) {
                            if (handleResponseData(res, layer)) {
                                // After successful deletion, reload the page setTimeout(function () {
                                    location.href = 'newsTypeList.html';
                                }, delayTime);
                            }
                        }
                    });
                    layer.close(index);
                }
            );
        }else {
            layer.msg('Please select at least one row', {icon: 3});
        }
    }
});

The public js file defines serverBase (request backend base address), delayTime (message pop-up delay time), and the handleResponseData function that encapsulates the returned data processing.

At this point, the two functions of the header toolbar have been realized. It’s relatively simple, right?

Monitor table row toolbar

table.on('tool(newsTypeList)', function (obj) {
    // Get the value corresponding to lay-event (or the value corresponding to the event parameter in the header)
    var layEvent = obj.event;
    // Get the row data object var data = obj.data;
    switch (layEvent) {
        case 'edit':
            const row = obj.tr;
            const field_td = row.find(`[data-field$=${field[0]}]`);
            field_td.data('edit', true);
            row[0].onclick = function() {
                setTimeout(function () {
                    field_td[0].lastChild.onblur = function () {
                        row.find('[data-field$=typeName]').data('edit', false);
                    }
                }, 10);
            };
            break;
        case 'del':
            let ids = [];
            ids.push(data.id);
            layer.confirm(`Are you sure you want to delete the row where ID => ${ids[0]} is located?`, function(index) {
                //Send delete command to the server$.ajax({
                    type: "DELETE",
                    contentType: "application/json;charset=UTF-8",
                    url: serverBase + "newsType/del",
                    data: JSON.stringify(ids),
                    dataType: 'json',
                    success: function (res) {
                        if (handleResponseData(res, layer)) {
                            setTimeout(function () {
                                // Delete the DOM structure of the corresponding row (tr) and update the cache obj.del();
                            }, delayTime);
                        }
                    }
                });
                layer.close(index);
            });
            break;
    }
});

Deleting a row is very simple. Just click on the row to get the ID of the object to be deleted, and pass it to the backend to delete the data of the corresponding row.

It is a bit difficult to implement editing by clicking the edit button in the line. First, after you click the button, you have to open the editing of the agreed field, that is, an input box will appear after clicking, and you can modify and update it. When the input box loses focus, you have to close the editing entrance just now, that is, the input box will not appear again when you click it again.

// Enable editing of the specified field. Similarly, pass false as parameter to disable it. obj.tr.find(`[data-field$=${field[0]}]`).data('edit', true);

Among them, field specifies the edit field name, which is consistent with the field attribute value in the cols attribute.

//Specify the edit field const field = ['typeName'];

Use the find function in JQuery to find the label corresponding to the cell, then use the data function to add the edit attribute and initialize it to the true value, which is equivalent to: {field: 'typeName', title: 'News Category', align: 'center', edit: true}

Since the input box appears after clicking the corresponding cell, a click event is registered for the cell. However, the input box cannot be obtained immediately after the click event. There is a delay in updating the DOM structure, and some time is needed to delay the acquisition.

Through browser debugging, it is found that the last child element in the parent element of the cell td is input. Add a focus loss event. When it is triggered, the editing entrance is closed and the button needs to be pressed again to open it.

row[0].onclick = function() {
    setTimeout(function () {
        field_td[0].lastChild.onblur = function () {
            row.find('[data-field$=typeName]').data('edit', false);
        }
    }, 10);
};

Listening cells

table.on('edit(newsTypeList)', function(obj) {
    let value = obj.value // Get the modified value, data = obj.data // Get all key values ​​in the row, field = obj.field; // Get the modified field let modifiedData = {id: data.id};
    modifiedData[field] = value;
    $.ajax({
        type: "POST",
        contentType: "application/json;charset=UTF-8",
        url: serverBase + 'newsType/update',
        data: JSON.stringify(modifiedData),
        dataType: 'json',
        success: function(res) {
            if(!handleResponseData(res, layer)) {
                setTimeout(function () {
                    location.href = 'newsTypeList.html';
                }, delayTime);
            }
        }
    });
});

Finally, the modified object is passed in and an update request is sent. The modified value can be verified in the background. If the modification fails, the current page is refreshed.

Conclusion

This is the end of this article about dynamic editing of data in Layui table rows. For more relevant Layui table dynamic editing content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Django Layui interface clicks on the pop-up dialog box and requests logic to generate a dynamic table instance with paging
  • Detailed explanation of dynamic changes of dynamic cols (fields) in layui data tables
  • How to change the table header and reload the table dynamically in layui table
  • Layui layout and table rendering as well as methods for dynamically generating tables
  • How to implement dynamic display of buttons in layui table operation column
  • Layui method to dynamically add a row to the data table and jump to the page where the added row is located

<<:  Solution to BT Baota Panel php7.3 and php7.4 not supporting ZipArchive

>>:  Briefly understand the MYSQL database optimization stage

Recommend

Several ways to encapsulate breadcrumb function components in Vue3

Table of contents Preface 1. Why do we need bread...

How to install mysql5.6 in docker under ubuntu

1. Install mysql5.6 docker run mysql:5.6 Wait unt...

Summary of several situations in which MySQL indexes fail

1. Indexes do not store null values More precisel...

How to use Vue to develop public account web pages

Table of contents Project Background start Create...

Detailed analysis of the principles and usage of MySQL views

Preface: In MySQL, views are probably one of the ...

Good website copywriting and good user experience

Looking at a website is actually like evaluating a...

Solution to forget password when installing MySQL on Linux/Mac

Preface This article mainly introduces the releva...

Tips for adding favicon to a website: a small icon in front of the URL

The so-called favicon, which is the abbreviation o...

Solutions to MySQL batch insert and unique index problems

MySQL batch insert problem When developing a proj...

How to parse the attribute interface of adding file system in Linux or Android

The first one: 1. Add key header files: #include ...

Tomcat CentOS installation process diagram

Tomcat CentOS Installation This installation tuto...

Summary of seven MySQL JOIN types

Before we begin, we create two tables to demonstr...