BootStrapTable新增一行数据,原有数据清空

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/header::commonHeader(~{::head/meta},~{::head/title},~{::head/link},~{::head/script},~{::head/style})">
    <meta charset="UTF-8">
    <title>工場マスタ</title>
    <link>
    <script></script>
    <style type="text/css">
        
    </style>
</head>
<body class="hold-transition sidebar-mini" style="height: 650px;">
    <div id="scroll-wrapper" class="wrapper">
        <form id="validation-form" method="post" role="form">
            <div class="container-fluid">
                <section class="content-header"><!-- ページヘッダー -->
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 style="text-align: left;" class="col-sm-6">工場マスタ</h1>
                        </div>
                    </div>
                </section>
                <section class="content"><!-- ページ内容 -->
                    <div class="col-md-8">
                        <div class="form-group row">
                            <label class="col-sm-1 col-form-label">工場コード</label>
                            <div class="col-sm-2">
                                <input type="text" id="searhKoJyoCd" class="form-control requiredbg input-rad"
                                    style="width: 121px;" maxlength="10" />
                            </div>
                            <div class="col-sm-2">
                                <input id="searchDeletekbn" name="searchDeletekbn" type="checkbox" class="form-check-input"
                                style="vertical-align: middle;" value="1">
                            <label class="form-check-label" for="searchDeletekbn">削除済みも表示</label>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group row">
                            <label class="col-sm-1 col-form-label">工場名</label>
                            <div class="col-sm-2">
                                <input type="text" id="searchKoJyoNm" class="form-control requiredbg input-rad"
                                    style="width: 121px;" maxlength="10" />
                            </div>
                            <button id="update" class="btn btn-danger" style="margin-left: 10px" type="button" onclick="research()">
                                <i class="fa fa-search"></i> 検 索
                            </button>
                            <button id="cancel" class="btn btn-secondary" style="margin-left: 10px" type="button" onclick="cancelDate()">
                                <i class="fa fa-times"></i> 取 消
                            </button>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group">
                            <button class="btn btn-primary" onclick="addRow();" type="button">
                                <span class="input-group-addon"> <i class="fa fa-plus"></i> </span> 追 加
                            </button>
                        </div>
                    </div>
                    <div class="col-md-8">
                        <div class="form-group" style="width: 1300px; height:500px; border: 1px solid rgba(204, 204, 204, 1);">
                            <table id="table" data-toggle="table" class="thead-light-gray" style="width: 1280px;">
                            </table>
                        </div>
                    </div>
                    <div class="col-md-8" style="height:40px">
                        <div class="form-group float-right" >
                            <button id="update" class="btn btn-primary" style="margin-left: 10px" type="button" onclick="insertData();">
                                <i class="fa fa-check"></i> 登 録
                            </button>
                            <button id="cancel" class="btn btn-secondary" style="margin-left: 10px" type="button" onclick="cancelop();">
                                <i class="fa fa-times"></i> 取 消
                            </button>
                        </div>
                    </div>
                </section><!-- ページ内容/END -->
            </div>
        </form>
    </div>

    <script type="text/javascript" th:inline="javascript">
    
    var deleteList = [];
    var submitData = {};
    // 进入工場マスター页面时,从后端返回到前端的数据
    var kojyokbnList = /*[[${formdata}]]*/ [];
    
    function insertData(){
    	var data = $('#table').bootstrapTable('getData');
    	console.log(data);
    	var length = $('#table').bootstrapTable('getData').length;
    	if(length == 0){
    		businessMessage.alert("E000025",11);
    		return;
    	}
    	if(length >= 100){
            businessMessage.alert("E000030",100);
            return;
        }
    	
    	submitData.tsmk01006Entities = data;
    	submitData.logicDeleteIds = deleteList;
    	
    	doAjax("/TSMK01006/save",submitData,function(data) { 
    		console.log(data);
            if(data.status == 'FAIL'){
                businessMessage.alert("I000005");
            } else if(data.status == 'SUCCESS'){
            	businessMessage.alert("I000003");
            	research();
            }
        })
    }
    
    function cancelop(){
    	window.location.reload();
    }
    
    /*
    	我们对表格中的输入框添加了失去焦点的操作,当失去焦点的时候,会把表格中输入的输入添加到整个表格对象中,
    	从而防止添加一行新数据后,原有的数据被清除
     */
    function changeData(tableId, index, obj) {
        var value = $(obj).val();
        var name = $(obj).attr('id');
        var row = $('#' + tableId).bootstrapTable('getData')[index];
        row[name] = value;
    }
    
    function cancelDate(){
    	$('#searhKoJyoCd').val('');
    	$('#searchKoJyoNm').val('');
    	$('#searchDeletekbn').prop("checked",false);
    }
    
    // 点击追加按钮,新添加一行数据
    function addRow(){
    	// 获取整个表格中所有的数据,并且计算其长度
        var rowCount = $('#table').bootstrapTable('getData').length;
        // 每增加一行表格,index都会增加1,从而实现表格一行行的进行添加
        index: rowCount + 1,
        $('#table').bootstrapTable('insertRow', {
        	// 
            index: rowCount + 1,
            row: {
            	// 新增列的索引,每增加一行索引就添加1
            	idx: rowCount + 1,
            	kojoCd: "",
                kojoNm: "",
                kojokbn: "",
                kojorkNm: "",
                jyusyo: "",
                yubin: "",
                telNo: "",
                faxNo: "",
                tantoNm: ""
            }
        });
    }
    
    // 删除新添加的数据
    function removeRow(index) {
    	$('#table').bootstrapTable('remove', {
            field : 'idx',
            values : [parseInt(index)]
        });
    }
    
    // 删除已经存在的数据
    function removeData(index,idx) {
    	var row = $("#table").bootstrapTable('getData')[index];
    	deleteList.push(row.kojoCd);
        $('#table').bootstrapTable('remove', {
            field : 'idx',
            values : [parseInt(idx)]
        });
    }
    
    
    /*削除*/
    function actionFormatterDelete(value, row, index) {
        if(row.deletekbn == "1"){
             return [
                    '<button class="btn btn-info btn-lg btn-size input-rad  font1-setFamliy" type="button" disabled = "true" style="cursor:default;">削 除</button>'
                ].join('');
        }else if(row.deletekbn == "0") {
            return [
                '<button class="btn btn-info btn-lg btn-size input-rad  font1-setFamliy" type="button" οnclick="removeData('+ index + ',' + row.idx + ');">削 除</button>'
            ].join('');
        }else {
            return [
                '<button class="btn btn-info btn-lg btn-size input-rad  font1-setFamliy" type="button" οnclick="removeRow('+ row.idx  + ');">取消</button>'
            ].join('');
        }
    };
    
    function kojoCdOperate(value,row,index){
        return [
            '<input type="text" id="kojoCd" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function kojoNmOperate(value,row,index){
        return [
            '<input type="text" id="kojoNm" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    // 根据工厂区分来显示下拉列表
    function kojokbnOperate(value,row,index){
    	var length = kojyokbnList.length;
    	var newRow = '<select id="kojokbn" class="select2 form-control no-border-select2" data-placeholder="" οnblur="changeData('+ 'table.id' + ',' + index + ', this);">'
 
   		for (var i = 0; i < length; i++) {
   			// 如果当前行的数据和后端返回的数据相等的话,就默认选中当前行的数据
   			if (row.kojokbn == kojyokbnList[i].value) {
                newRow += '<option selected="selected" value="' + kojyokbnList[i].value + '">' + kojyokbnList[i].text
                        + '</option>';
            } else {
                newRow += '<option value="' + kojyokbnList[i].value + '">' + kojyokbnList[i].text + '</option>';
            }
        }
    	
    	newRow += '</select>';
        return [ newRow ].join('');
    }
    
    function kojorkNmOperate(value,row,index){
        return [
            '<input type="text" id="kojorkNm" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function jyusyoOperate(value,row,index){
        return [
            '<input type="text" id="jyusyo" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function yubinOperate(value,row,index){
        return [
            '<input type="text" id="yubin" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function telNoOperate(value,row,index){
        return [
            '<input type="text" id="telNo" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function faxNoOperate(value,row,index){
        return [
            '<input type="text" id="faxNo" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function tantoNmOperate(value,row,index){
        return [
            '<input type="text" id="tantoNm" class="form-control number-input" dec="2"" style="text-align:right" maxLength="7" value="' + value + '" οnchange="changeData('+'table.id'+','+ index +', this);">'
        ].join('');
    }
    
    function idxOperate(value,row,index){
        // number タイプ
    	return index;
    }
    
    // 検索ボンタンを押す
    function research() {
        // 検索条件を取得する
        var submitData = getJsonObject("scroll-wrapper");
        submitData.searchKojoCd = $.trim($("#searhKoJyoCd").val());
        submitData.kojoNm =  $.trim($("#searchKoJyoNm").val());
     
        // Ajaxで検索を行う
        //商品一覧のデータを検索する
        doAjax("/TSMK01006/search", submitData,function(data) { 
        	
        	if(data.status == 'FAIL'){
        		businessMessage.alert("I000002");
        	}
        	// 把检索到的数据加载到表格对象中
            $("#table").bootstrapTable('load', data.data);
        })
    };

    /*bootstrap tableの項目*/
    initBootstrapTable("table", {
        reorderableRows: true,
        striped: true,
        toolbar: '#toolbar',
        useRowAttrFunc: true,
        method: 'get',
        url: '',
        theadClasses: "thead-blue",
        btn: true,
        height: 500,
        width: 1180,
        columns: [
            [{
                field: 'idx',
                title: 'idx',
                align: 'center',
                colspan: 1,
                width: 80,
                halign: "center",
                sortable: true,
                visible: false
            },{
                field: 'kojoCd',
                title: '工場コード',
                align: 'center',
                colspan: 1,
                width: 80,
                halign: "center",
                sortable: true,
                formatter:kojoCdOperate,
            }, {
                field: 'kojoNm',
                title: '工場名',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 120,
                halign: "center",
                sortable: true,
                formatter:kojoNmOperate,
            }, {
                field: 'kojokbn',
                title: '工場区分',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 70,
                halign: "center",
                sortable: true,
                formatter:kojokbnOperate
            }, {
                field: 'kojorkNm',
                title: '工場名略称',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 100,
                halign: "center",
                sortable: true,
                formatter:kojorkNmOperate,
            }, {
                field: 'jyusyo',
                title: '住所',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 108,
                halign: "center",
                sortable: true,
                formatter:jyusyoOperate,
            }, {
                field: 'yubin',
                title: '郵便番号',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 50,
                halign: "center",
                sortable: true,
                formatter:yubinOperate,
            }, {
                field: 'telNo',
                title: '電話番号',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 95,
                halign: "center",
                sortable: true,
                formatter:telNoOperate,
            }, {
                field: 'faxNo',
                title: 'FAX',
                class: "readonly-column",
                align: 'left',
                colspan: 1,
                width: 130,
                halign: "center",
                sortable: true,
                formatter:faxNoOperate,
            }, {
                field: 'tantoNm',
                title: '担当者',
                class: "readonly-column",
                align: "left",
                colspan: 1,
                width: 80,
                halign: "center",
                sortable: true,
                formatter:tantoNmOperate,
                
            }, {
                field: 'deletekbn',
                title: '削除',
                class: "readonly-column",
                align: "right",
                colspan: 1,
                width: 80,
                formatter: actionFormatterDelete
            }]
        ],
    });
    

    </script>
</body>

</html>
<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Hello, Bootstrap Table!</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css">
</head>
<body>
    <!--表格的区域-->
    <table id="table" style="width: 500px;height: 800px">

    </table>

<br>
<button id="addData" onclick="addData()">追加</button>
<br>
<button id="btn" onclick="addFormList()">登录</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js" integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js" integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k" crossorigin="anonymous"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>
</body>
<script>

    // 全局变量,向后端发送的数据对象
    var obj = {};
    // 全局数组,存放删除的列表,用来向后端发送请求时使用
    var list = [];

    /**
     * 初始化表格
     * */
    $('#table').bootstrapTable({
        url:"/index/search",
        //表格的列
        columns: [
            {
                field: 'timestamp',//域值
                title: '时间戳',//标题
                sortable: true,//启用排序
                formatter: timeOperate
            },
            {
                field: 'id',//域值
                title: 'ID',//标题
                sortable: true,//启用排序
                formatter: idOperate
            },
            {
                field: 'name',//域值
                title: '姓名',//标题
                sortable: true,//启用排序
                formatter: nameOperate

            },
            {
                field: 'age',
                title: '年龄',
                formatter: ageOperate
            },
            {
                field: 'address',
                title: '状态',
                sortable: true,
                formatter: addressOperate
            },
            {
                field: 'deleteFlag',
                title: '按钮',
                formatter : deleteFlag
            }
        ]
    });

    // 点击登录按钮,把表格中输入的数据提交到后端
    function addFormList() {
        // 我们可以通过传入index索引来获取行对象,通常在删除数据的时候会用到
        // var row = $('#table').bootstrapTable('getData')[index]

        // 获取整个表格的所有数据
        var data = $('#table').bootstrapTable('getData');

        // 获取整个表格数据的长度
        var count = data.length;
        /**
         * 把插入的数据更新到表格当中
         * 之所以要在登录之前调用这个函数是因为用户输入完追加表格的数据之后,只有调用updataData()方法
         * 才能把数据更新到整个表格对象中
         * */
        updataData(count);

        // 向全局对象中封装数据,students和deleteIdList命名要和后端的封装属性保持一致,否则后端无法接收参数
        obj.students = data;
        obj.deleteIdList = list;

        console.info(JSON.stringify(obj));
        // 向后端发送post请求,提交前端输入好的数据
        $.ajax({
            url : '/index/insert',
            type: "POST",
            datatype:"json",
            contentType: "application/json;charset=utf-8",
            data:JSON.stringify(obj),
            success : function(data, stats) {
                console.log(data);  // {age1: 108,name1: "jiamingwei添加铭威"}
                console.log(stats);  // success
            },
            error : function(data) {
                alert("请求失败");
            }
        })
    }

    // 更新表格的数据
    function updataData(count){
        // 创建一个数组,用来存放表格中所有的数据
        var params = [];
        for(var dataIndex=0;dataIndex<=count;dataIndex++) {
            // 使用JQuery选择器找到td标签(也就是包含input标签的标签)对象,这种选法选中了很多td标签,因此需要遍历
            var columns = $('#table tr[data-index="'+dataIndex+'"] td');
            // 创建一个对象.用来存放表格中一行的数据
            var obj = {};
            for (var i=0; i < columns.length -1; i++) {
                // 对td标签进行遍历,遍历出一个个的tr标签(tr标签内包含有input标签)
                // 找到tr标签内的input对象
                var td = $(columns[i]).find('input');
                // 获取id属性所对应的值
                var key = td.attr('id');
                // 获取input输入框内已经输入的值(添加$.trim()是为了防止更新的时候添加很多空的字符串)
                obj[key] = $.trim(td.val());
            }
            /*
            * {index:索引值, row:每行索引对应的数据(是一个对象)}
            * 表格中每一行的数据
            * {index:0, row:{id: "1", name: "XXX", age: "18", address: "XX"}}
            * {index:1, row:{id: "1", name: "XXX", age: "20", address: "XX"}}
            * */
            params.push({index:dataIndex, row:obj});
        }
        console.info(params);
        // 对表格中的数据进行更新
        $('#table').bootstrapTable("updateRow",params);
    }

    // 追加一行新数据
    function addData() {
        var count = $('#table').bootstrapTable('getData').length;

        // 在插入之前先更新表格的数据
        updataData(count);

        $('#table').bootstrapTable('insertRow', {
            // 若删除,则无法追加新列.每增加一行新列就会给索引增加一位
            index: count + 1,
            // 初始化新添加的行中的值(因为是新添加的,所以值为空)
            row: {
                // 每增加一行的时候添加一个时间戳
                timestamp: (new Date()).valueOf(),
                id: '',
                name: '',
                age: '',
                address : ''
            }
        });
    }

    function deleteFlag(value, row, index) {
        // 根据不同的情况显示不同状态下的按钮
        if (row.deleteFlag == false){
            return '<button οnclick="deleteData('+ row.timestamp + ',' +  index + ')">删除</button>'
        } else if (row.deleteFlag == true){
            return '<button disabled="disabled">删除</button>'
        }
        else {
            return '<button οnclick="deleteInsert('+ row.timestamp +')">取消</button>'
        }
    }

    function deleteData(timestamp,index) {
        var row = $("#table").bootstrapTable('getData')[index];
        // 把要删除的数据的id放到list列表中
        list.push(row.id);
        $('#table').bootstrapTable('remove', {
            field: 'timestamp',
            // values所对应的一定要是一个数组,否则会报错
            values: [parseInt(row.timestamp)]
        });
    }

    function deleteInsert(timestamp) {
        $('#table').bootstrapTable('remove', {
            field: 'timestamp',
            values: [parseInt(timestamp)]
        });
    }

    function idOperate(row,index,vaue){

        return [
            '<input type="text" id="id" class="form-control" style="width: 80px;" value=" '+row+' " />'
        ].join('');
    }

    function nameOperate(row,index,vaue){
        return [
            '<input type="text" id="name" class="form-control" style="width: 80px;" value=" '+row+' " />'
        ].join('')
    }

    function ageOperate(row,index,vaue){

        return [
            '<input type="text" id="age" class="form-control" style="width: 80px;" value=" '+row+' " />'
        ].join('')
    }

    function addressOperate(row,index,vaue){
        return [
            '<input type="text" id="address" οnblur="testOBj()" class="form-control" style="width: 80px;" value=" '+row+' " />'
        ].join('')
    }

    // 给查询到的每一行数据添加时间戳
    function timeOperate(row,index,vaue){
        return [
            (new Date()).valueOf()
        ].join('')
    }

    function testOBj() {
        var obj = $('input').val();
        console.info(obj);
    }

</script>
</html>
发布了19 篇原创文章 · 获赞 2 · 访问量 6556

猜你喜欢

转载自blog.csdn.net/feyehong/article/details/105323506