jquery easyui DataGrid Simple Example

  • 2021-07-13 04:17:34
  • OfStack

1. Simple example

HTML


<table id="tbList" striped="true" rownumbers="true" fix="true" fitcolumns="true" title=" Title "
    idfield="ID" checkbox="true" url="@Url.Action("ListData")">
  <thead>
    <tr>
      <th field="ID" checkbox="true" width="30">
      </th>
      <th field="Name" width="200" align="center">
         Name 
      </th> 
    </tr>
  </thead>
</table>

JS


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});

2. Basic usage

Frozen column


$('#tbList').datagrid({ pagination: true,
      frozenColumns: [[
      { field: 'BId',checkbox:'true',width:30},
      { field: 'BNo', title: ' Brand ', width: 100 },
      { field: 'FNo', title: ' Class number ', width: 100 }
            ]], 
                             fitColumns:false   // Disable adaptive width and can scroll horizontally 
    });

Remove paging


$('#tbList').datagrid({pagination: true});

Change to


$('#tbList').datagrid();

Or


$('#tbList').datagrid({pagination: false});

Note: At the same time, the height of table needs to be set, and it cannot be auto

Check box and radio


<table id="tbList" style="height: 330px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit" 
checkbox="true" idfield="Id" url="@Url.Action("ListData")">
<thead>
    <tr>
       <th field="Id" checkbox="true" width="150">
        </th>
          </tr>
</thead>
</table>

Change to radio (add singleSelect= "true")


<table id="tbList" style="height: 330px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit" singleSelect="true" checkbox="true"  idfield="Id" url="@Url.Action("ListData")">

Select all by default after loading data:


 $(document).ready(function () {
    $('#tbList').datagrid({ 
      onLoadSuccess: function (data) {
        $('#tbList').datagrid('selectAll');
      } 
    });

Get the number of rows


$('#tbList').datagrid("getRows").length;

Hide column


<th field="Dept" width="100" hidden="true"> Name </th>

Empty the original data

Method 1:


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
0

Method 2: (tested)


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
1

Parsing: loadData: Load local data, old records will be removed.

Row click event


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
2

datagrip When you click a row, set the radio button to select


<script type="text/javascript">
  var List = {};
  List.RadioFormatter = function (value, rec, index) {
    return "<input id='radio_id' name='radio_name' type='radio' value='" + rec.Id + "'/>";
  };

   $(document).ready(   function(){ // Render list data 
        $('#tbList').datagrid({ onClickRow:
      function () {
        // When you click a row, set the radio button to select 
        var id = $('#tbList').datagrid("getSelected");
        $("input[name='name']").each(function () {
          if ($(this).val() == id.Id) {
            $(this).attr("checked", true);
          }
        });
      }
    });
});
</script>
<table id="tbList" style="height: 300px;" striped="true" rownumbers="true" fitColumns="true" title="" iconcls="icon-edit"
     singleSelect="true" checkbox="true" idfield="Id" url="@Url.Action("ListData")">
      <thead>
        <tr>
          <th field="Id" width="30" formatter="PickupList.RadioFormatter">
          </th>
        </tr>
      </thead>
    </table>

Time Format of td in table

1. Pages


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
4

2.js


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
5

td content in table is too long to wrap lines

Add attribute nowrap = "false"

Set the nowrap: false attribute in the table attribute, not in the field attribute, the field can set the width, so that when the text length exceeds the specified width, it can wrap automatically

Separation of rows and check boxes

Method 1: (version 1.3 can only be used)


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
6

Note: When using $("# tbList"). datagrid ("getSelections"); Only when the row is selected can the row be fetched. 1 In general, when the row is selected, the behavior has a yellow background.

eg. < table checkOnSelect="false" > < /table >


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
7

Method 2 (solution before version 1.3)


var IsCheckFlag = true;
    $('#tbList').datagrid({
      pagination: true,
      onClickCell: function (rowIndex, field, value) {
        IsCheckFlag = false;
      },
      onSelect: function (rowIndex, rowData) {
        if (!IsCheckFlag) {
          IsCheckFlag = true;
          $("#tbList").datagrid("unselectRow", rowIndex);
        }
      },
      onUnselect: function (rowIndex, rowData) {
        if (!IsCheckFlag) {
          IsCheckFlag = true;
          $("#tbList").datagrid("selectRow", rowIndex);
        }
      }
    });

Style the data list


$('#tbList').datagrid({ pagination: true });
$("#btnSearch").click(function () {// Query method 
  $('#tbList').datagrid("unselectAll");
  $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val()} });
});
9

Conditional query

bug of check box: When using parameter query, the option selected before query, after query, use getSelections method to get it, and it still exists

Solution: Clear the check box before querying through unselectAll


$("#btnSearch").click(function () {
      $('#tbList').datagrid("unselectAll");
      $('#tbList').datagrid({ queryParams: { SearchName: $("#SearchName").val() } });
    });

Query bug: When using parameter query, after query, the current page number displayed is still previous, and will not be reset to 1 or previous page number; If the current total number of pages is smaller than the current number, the page will appear empty. For example, on the current page 3, after adding the time query, there is only one page of data, so the current page number is still 3, resulting in a blank page.

Solution: Set pageNumber to 1


$("#btnSearch").click(function () {
      $('#tbList').datagrid("unselectAll");
      $('#tbList').datagrid({ pageNumber: 1,queryParams: { SearchName: $("#SearchName").val() } });
    });

3. Addition, deletion and modification of row data

HTML (No Paged List)


<table id="tbProductList" style="height: 500px; max-height: 500px;" fix="true" fitcolumns="true" idfield="ID" url="@Url.Action("ListData")"></table>

JS


$(document).ready(function () { 
    var datagrid;
    var editRow = undefined;
    datagrid = $("#tbList").datagrid({
      border: true,
      checkbox: true,
      iconCls: 'icon-save', //图标
      nowap: true, //列内容多时自动折至第2行
      pagination: false,
      rownumbers: true,
      striped: true, //行背景交换
      columns: [[//显示的列
       { field: 'ID', title: '编号', width: 100, align: 'center', sortable: true, checkbox: true },
       { field: 'Name', title: '名称', width: 100, sortable: true },
       {
         field: 'PriceType', title: '类型', width: 100, align: 'center',
         formatter: function (value, row) { return row.TypeName; },
         editor: {
           type: 'combobox', options: {
             valueField: 'Value',
             textField: 'Text',
             method: 'get',
             url: $("#TypeUrl").val(),
             required: true
           }
         }
       },
        {
          field: 'Price', title: '价格', width: 100, align: 'center',
          editor: {
            type: 'numberbox', options: {
              required: true,
              min: 0,
              precision: 2
            }
          }
        },
        {
          field: 'Count', title: '数量', width: 100, align: 'center',
          editor: {
            type: 'numberbox', options: {
              required: true,
              min: 0,
              precision: 0
            }
          }
        }
      ]],
      queryParams: { action: 'query' }, //查询参数
      toolbar: [{ text: '添加', iconCls: 'icon-add', handler: function () {//添加列表的操作按钮添加,修改,删除等
          //添加时先判断是否有开启编辑的行,如果有则把开户编辑的那行结束编辑
          if (editRow != undefined) {
            datagrid.datagrid("endEdit", editRow);
          }
          //添加时如果没有正在编辑的行,则在datagrid的第1行插入1行
          if (editRow == undefined) {
            datagrid.datagrid("insertRow", {
              index: 0, // index start with 0
              row: {

              }
            });
            //将新插入的那1行开户编辑状态
            datagrid.datagrid("beginEdit", 0);
            //给当前编辑的行赋值
            editRow = 0;
          }

        }
        }, '-',
       {
         text: '删除', iconCls: 'icon-remove', handler: function () {
           //删除时先获取选择行
           var rows = datagrid.datagrid("getSelections");
           //选择要删除的行
           if (rows.length > 0) {
             $.messager.confirm("提示", "你确定要删除吗?", function (r) {
               if (r) {
                 var ids = [];
                 for (var i = 0; i < rows.length; i++) {
                   ids.push(rows[i].ID);
                 } 
                 //将选择到的行存入数组并用,分隔转换成字符串
                 if ($.trim(ids) != "") {
                  //---- Delete(ids.join(','));//这是post
                 } else {
                   alert("请选择要删除的信息!");
                 }
               }
             });
           }
           else {
             $.messager.alert("提示", "请选择要删除的行", "error");
           }
         }
       }, '-',
       {
         text: '修改', iconCls: 'icon-edit', handler: function () {
           //修改时要获取选择到的行
           var rows = datagrid.datagrid("getSelections");
           //如果只选择了1行则可以进行修改,否则不操作
           if (rows.length == 1) {
             //修改之前先关闭已经开启的编辑行,当调用endEdit该方法时会触发onAfterEdit事件
             if (editRow != undefined) {
               datagrid.datagrid("endEdit", editRow);
             }
             //当无编辑行时
             if (editRow == undefined) {
               //获取到当前选择行的下标
               var index = datagrid.datagrid("getRowIndex", rows[0]);
               //开启编辑
               datagrid.datagrid("beginEdit", index);
               //把当前开启编辑的行赋值给全局变量editRow
               editRow = index;
               //当开启了当前选择行的编辑状态之后,
               //应该取消当前列表的所有选择行,要不然双击之后无法再选择其他行进行编辑
               datagrid.datagrid("unselectAll");
             }
           }
         }
       }, '-',
       {
         text: '保存', iconCls: 'icon-save', handler: function () {
           //保存时结束当前编辑的行,自动触发onAfterEdit事件如果要与后台交互可将数据通过Ajax提交后台
           datagrid.datagrid("endEdit", editRow);
         }
       }, '-',
       {
         text: '取消编辑', iconCls: 'icon-redo', handler: function () {
           //取消当前编辑行把当前编辑行罢undefined回滚改变的数据,取消选择的行
           editRow = undefined;
           datagrid.datagrid("rejectChanges");
           datagrid.datagrid("unselectAll");
         }
       }, '-'],
      onAfterEdit: function (rowIndex, rowData, changes) {
        //endEdit该方法触发此事件
        //console.info(rowData);
        //---- Update(ids.join(','));//这是post
        editRow = undefined;
      },
      onDblClickRow: function (rowIndex, rowData) {
        //双击开启编辑行
        if (editRow != undefined) {
          datagrid.datagrid("endEdit", editRow);
        }
        if (editRow == undefined) {
          datagrid.datagrid("beginEdit", rowIndex);
          editRow = rowIndex;
        }
      }
    });
  });


Related articles: