current position:Home>Dynamic editing of data in layui table rows

Dynamic editing of data in layui table rows

2021-08-27 07:25:56 HUALEI

Preface

This is my participation 8 The fourth of the yuegengwen challenge 4 God , Check out the activity details :8 Yuegengwen challenge . Coincides with the Nuggets August is more challenging , Today, I'd like to share some information about the classic front-end framework layui Dynamic table data operation in , combination JQuery Dynamically edit the data in the cell , I hope I can help those in need , come on. , Mutual encouragement !

Style function description

image.png

Initialization code

according to Layui Developing documents , We can easily write the following code , Load built-in components , Dynamic table data filling :

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
            };
        },
        //  Open 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: ' Show a lonely ~'
        }
    });
});
 Copy code 

explain

First, by requesting background data , Assign the requested data through data analysis , Be careful : If paging is turned on , The total number of items that need to be displayed by back-end delivery , When opening a page, the default paging request sent is ...?page=1&limit=10 , adopt request Property to change the passed parameter name , For example, my paging request is changed to ...all?offset=1&pageSize=10 .

Open the toolbar after , The default header toolbar on the right will open , If not, you need to defaultToolbar Property value is empty , And when you customize toobar when ,HTML Label elements need to be placed in div The Chinese side of the label can take effect , This is a rule .

toobar Use in Layui The template syntax verifies the current administrator permissions , If you do not have this permission, it will not be displayed .

adopt {type: 'checkbox', fixed: 'left'} Turn on the check box , And fix it to the far left in the table .

In the operation bar , adopt id Introduce external customization toolbar

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

Add listening Events

Monitor header toolbar

table.on('toolbar(newsTypeList)', function(obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    //  Select row data 
    let selectedData = checkStatus.data;
    if(obj.event === 'add') {
        //  Jump to the news type add 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(` confirm deletion  ID[${ids}]  Do you ?`, {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 page 
                                setTimeout(function () {
                                    location.href = 'newsTypeList.html';
                                }, delayTime);
                            }
                        }
                    });
                    layer.close(index);
                }
            );
        }else {
            layer.msg(' Please select at least one row ', {icon: 3});
        }
    }
});
 Copy code 

public js It's defined in the file serverBase( Request backend base address )、delayTime( Message layer delay time ) And encapsulating the functions that process the returned data handleResponseData . Here we are , The two functions of the header toolbar are realized , It's a little bit easier , Right ?

image.png

Listen to the table row toolbar

table.on('tool(newsTypeList)', function (obj) {
    //  get  lay-event  Corresponding value ( It can also be in the header  event  The corresponding value of the parameter )
    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(` Really delete  ID => ${ids[0]}  Is it ok ?`, function(index) {
                // Send delete instruction 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 corresponding line (tr) Of DOM structure , And update the cache 
                                obj.del();
                            }, delayTime);
                        }
                    }
                });
                layer.close(index);
            });
            break;
    }
});
 Copy code 

Line deletion is simple , Click the line to get the deleted object id , The data of the corresponding row can be deleted by passing it to the back end .

It is a little difficult to click the Edit button to edit in the line , First you click the button , To open the edit of the contract field , That is, after clicking, an input box will appear , You can modify and update it , When the input box loses focus , Close the editing entry just now , That is, when you click again, the input box will not appear again .

//  Turn on the editing of the specified field , Close the same , Parameters of the incoming  false  that will do 
obj.tr.find(`[data-field$=${field[0]}]`).data('edit', true);
 Copy code 

among ,field Specify the edit field name , and cols Properties of the field Property values are consistent .

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

adopt JQuery in find Function to find the label corresponding to the cell , Re pass data The function adds edit attribute , And initialize it to true value , amount to :{field: 'typeName', title: ' News category ', align: 'center', edit: true}

Because the input box appears after clicking the corresponding cell , So register a click event for the cell , You can't get... Immediately after clicking the event input Input box , need DOM There is a delay in updating the structure , You need to delay the acquisition time .

Found through browser debugging , This cell td The last child element of the parent element is input , Add out of focus event , When triggered , Close the edit entry , It is necessary to press the button again to turn on .

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

Listen to cells

table.on('edit(newsTypeList)', function(obj) {
    let value = obj.value //  Get the modified value 
        , data = obj.data //  Get all the key values of the line 
        , 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);
            }
        }
    });
});
 Copy code 

Last , Pass in the modified object and send an update request , The modified value can be verified in the background , If the modification fails, refresh the current page .

ending

Last , Thank you very much for seeing this , Your attention 、 Comments and even praise are my unremitting motivation for learning and persistence !!

copyright notice
author[HUALEI],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827072552415y.html

Random recommended