Simple jquery easyui DataGrid example: jqueryeasyui

Source: Internet
Author: User
Tags datagrid example

Simple jquery easyui DataGrid example: jqueryeasyui

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 ()}});});

Ii. Basic usage

Freeze Columns

$ ('# TbList '). datagrid ({pagination: true, frozenColumns: [{field: 'bid', checkbox: 'true', width: 30}, {field: 'bno', title: 'fno', width: 100}, {field: 'fno', title: 'shift No. ', width: 100}], fitColumns: false // disable adaptive width and horizontal scrolling });

Remove pages

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

Change

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

Or

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

Note: At the same time, you must set the table height, and it cannot be auto

Check box and single choice

<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 single choice (add singleSelect = "true ")

Copy codeThe Code is as follows:
<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") ">

By default, all data are loaded:

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

Obtain the number of rows

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

Hide Columns

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

Clear original data

Method 1:

 var item = $('#filegrid').datagrid('getRows');      if (item) {        for (var i = item.length - 1; i >= 0; i--) {          var index = $('#filegrid').datagrid('getRowIndex', item[i]);          $('#filegrid').datagrid('deleteRow', index);        }      }

Method 2: (tested)

$('#filegrid').datagrid('loadData', { total: 0, rows: [] });

Parsing: loadData: loads local data, and old records are removed.

Row Click Event

$ ('# TbList'). datagrid ({onClickRow: function () {// code }});

When you click a row in the datagrip, 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 () {// present list data $ ('# tbList '). datagrid ({onClickRow: function () {// when you click a row, set the single-choice 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. Page

 <th field="Test" formatter="Common.TimeFormatter" width="50" ></th>

2. js

Var Common = {// use the DataGrid to format TimeFormatter: function (value, rec, index) {if (value = undefined) {return "";} /* convert json format time to js time format */value = value. substr (1, value. length-2); var obj = eval ('+ "{Date: new" + value + "}" + ')'); var dateValue = obj ["Date"]; if (dateValue. getFullYear () <1900) {return "";} var val = dateValue. format ("yyyy-mm-dd HH: MM"); // control format return val. substr (11, 5 );}};

The content of td in table is too long for automatic line feed

Add property nowrap = "false"

Set the nowrap: false attribute to the table attribute. Do not set it to the attribute of the field. You can set the width of the field, in this way, the text will be automatically wrapped when the text length exceeds the specified width.

Separation of rows and check boxes

Method 1: (version 1.3 is available)

checkOnSelect="false" selectOnCheck="false"

Note: When $ ("# tbList"). datagrid ("getSelections"); is used, this row can be obtained only when the row is selected. Generally, when a row is selected, the behavior is yellow.

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

Var selected = $ ("# tbList"). datagrid ("getSelections"); if (selected. length = 0) {alert ("Select! "); Return;} var idString =" "; $. each (selected, function (index, item) {idString + = item. Id + ",";});

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);        }      }    });

Set the style of the Data list

$ (Document ). ready (function () {// present list data $ ('# tbList '). datagrid ({pagination: true, rowStyler: function (index, row) {if (row. ID <10) {// If the id field of the data is smaller than 10, the return 'color: #999; 'is displayed as a gray font ;'; // The same style as the general style }}});});

Conditional Query

Check box bug: When you use parameter query, the selected option is obtained before the query. After the query, you can use the getSelections method to obtain the option. This option still exists.

Solution: Use unselectAll to clear the check box before querying.

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

Query bug: When parameter query is used, the current page number displayed after the query is still the previous one, not reset to 1 or the previous page number; if the current total page number is smaller than the current one, the page is displayed blank. For example, if there is only one page of data added to the Time query on the current third page, the current page number is 3, leading to 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 (non-Paging List)

Copy codeThe Code is as follows:
<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', // The nowap: true icon, // pagination: false, rownumbers: true, striped: true, // row background exchange columns: [[// displayed column {field: 'id', title: 'number', width: 100, align: 'center', sortable: true, checkbox: true}, {field: 'name', title: 'name', width: 100, Sortable: true}, {field: 'pricetype ', title: 'type', 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: 'price', width: 100, align: 'center', editor: {type: 'numberbox', options: {required: true, Min: 0, precision: 2 }}, {field: 'Count', title: 'quantity', width: 100, align: 'center', editor: {type: 'numberbox', options: {required: true, min: 0, precision: 0 }}]], queryParams: {action: 'query'}, // query parameter toolbar: [{text: 'add', iconCls: 'icon-add', handler: function () {// add list OPERATION button add, modify, delete and so on // when adding an account, determine whether there are rows for editing. if yes, end the line for account opening and editing if (editRow! = Undefined) {datagrid. datagrid ("endEdit", editRow);} // if no row being edited is added, insert a row if (editRow = undefined) {datagrid in the first row of the datagrid. datagrid ("insertRow", {index: 0, // index start with 0 row :{}}); // edit the status of the newly inserted row. datagrid ("beginEdit", 0); // assign editRow = 0 ;}}, '-', {text: 'delete', iconCls: 'icon-delete', handler: function () {// obtain the selected row var rows = datagrid before deletion. datagrid ("getSelection S "); // select the row to be deleted if (rows. length> 0) {$. messager. confirm (" prompt "," Are you sure you want to delete it? ", Function (r) {if (r) {var ids = []; for (var I = 0; I <rows. length; I ++) {ids. push (rows [I]. ID);} // Save the selected rows to an array and separate them into strings if ($. trim (ids )! = "") {// ---- Delete (ids. join (','); // This is post} else {alert ("select the information to Delete! ") ;}}) ;}Else {$. messager. alert ("prompt", "select the row to be deleted", "error") ;}}, '-', {text: 'modify', iconCls: 'icon-edit', handler: function () {// you need to obtain the selected row var rows = datagrid during modification. datagrid ("getSelections"); // you can modify it if only one row is selected. Otherwise, if (rows. length = 1) {// close the enabled edit row before modification. When the endEdit method is called, The onAfterEdit event if (editRow! = Undefined) {datagrid. datagrid ("endEdit", editRow);} // if (editRow = undefined) {// obtain the subscript var index = datagrid of the currently selected row when no row is edited. datagrid ("getRowIndex", rows [0]); // enables the edit datagrid. datagrid ("beginEdit", index); // assign the currently editable row to the global variable editRow = index; // when the editing status of the currently selected row is enabled, // cancel all selected rows in the current list. Otherwise, you cannot select other rows to edit the datagrid after double-clicking. datagrid ("unselectAll") ;}}}, '-', {text: 'save', iconCls: 'icon-save', handler: Function () {// ends the current edited row when the row is saved. The onAfterEdit event is automatically triggered. to interact with the background, submit the data to the background datagrid through Ajax. datagrid ("endEdit", editRow) ;}, '-', {text: 'unedit', iconCls: 'icon-redo ', handler: function () {// cancel the current edit row to roll back the changed data of the current edit row, and cancel the selected row editRow = undefined; datagrid. datagrid ("rejectChanges"); datagrid. datagrid ("unselectAll") ;}}, '-'], onAfterEdit: function (rowIndex, rowData, changes) {// endEdit this method triggers this event // console. Info (rowData); // ---- Update (ids. join (','); // This is post editRow = undefined;}, onDblClickRow: function (rowIndex, rowData) {// double-click to enable the edit row if (editRow! = Undefined) {datagrid. datagrid ("endEdit", editRow);} if (editRow = undefined) {datagrid. datagrid ("beginEdit", rowIndex); editRow = rowIndex ;}}});});

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.