2013年5月28日 星期二

jQuery EasyUI DataGrid Checkbox 資料設定與取值

純粹做個記錄,以免日後忘記該怎麼設定。

這一篇將會說明兩種使用 jQuery EasyUI DataGrid 的 Checkbox 設定方式,以及在既有資料下將 checked 為 true 的該筆資料列的 Checkbox 設定為 Checked,另外就是兩種 Checkbox 設定方式下如何取得有勾選的資料。

 


有關 jQuery EasyUI DataGrid 的相關資料,可以前往官網查看,

jQuery EasyUI 官網

jQuery EasyUI Documentation

DataGrid Demo

CheckBox select on DataGrid

 

使用的範例 JSON 資料:

{
  "total": 4,
  "rows": [
    {
      "productid": "FI-SW-01",
      "productname": "Koi",
      "unitcost": 10.00,
      "status": "P",
      "listprice": 36.50,
      "attr1": "Large",
      "itemid": "EST-1",
      "checked": true
    },
    {
      "productid": "K9-DL-01",
      "productname": "Dalmation",
      "unitcost": 12.00,
      "status": "P",
      "listprice": 18.50,
      "attr1": "Spotted Adult Female",
      "itemid": "EST-10",
      "checked": true
    },
    {
      "productid": "RP-SN-01",
      "productname": "Rattlesnake",
      "unitcost": 12.00,
      "status": "P",
      "listprice": 38.50,
      "attr1": "Venomless",
      "itemid": "EST-11",
      "checked": true
    },
    {
      "productid": "RP-SN-01",
      "productname": "Rattlesnake",
      "unitcost": 12.00,
      "status": "P",
      "listprice": 26.50,
      "attr1": "Rattleless",
      "itemid": "EST-12",
      "checked": false
    }
  ]
}

 

設定方式一:使用預設的設定方式

網頁的 HTML 原始碼內容

<body>
    <h2>Custom CheckBox on DataGrid</h2>
    
    <input type="button" id="ButonGetCheck" value="Get Checked" />
    <br/><br/>
    
    <table id="dg"></table>
    
</body>

我是習慣把 DataGrid 的相關設定放在 Javascript 程式中,因為這會比直接在 HTML 的 Table Tag 使用屬性設定的方式還具有彈性,

Javascript 程式中的 DataGrid 設定

$('#dg').datagrid({
    title: 'CheckBox Selection on DataGrid',
    url: 'datagrid_data3.json',
    width: '700',
    rownumbers: true,
    columns:[[
        { field:'ck',checkbox:true }, 
        { field: 'productid', title: 'productid' },
        { field: 'productname', title: 'productname' },
        { field: 'unitcost', title: 'unitcost' },
        { field: 'status', title: 'status' },
        { field: 'listprice', title: 'listprice' },
        { field: 'itemid', title: 'itemid' }
    ]],
    singleSelect: false,
    selectOnCheck: true,
    checkOnSelect: true
});

設定完成後的頁面如下:

image

但是我們的 JSON 資料裡有個欄位是「checked」,這個欄位的資料 true / false 就是用來設定 Checkbox 是否勾選,而設定的動作必須要在 DataGrid 載入資料完成後再去執行,這邊會使用到 jQuery 的 each 去逐一檢查每個資料列的的資料內容,假如 checked 為 true,那就使用「checkRow」這個 Method 將該資料列的 Checkbox 設為勾選的狀態,

image

修改後的 DataGrid 設定程式如下:

$('#dg').datagrid({
    title: 'CheckBox Selection on DataGrid',
    url: 'datagrid_data3.json',
    width: '700',
    rownumbers: true,
    columns:[[
        { field:'ck',checkbox:true }, 
        { field: 'productid', title: 'productid' },
        { field: 'productname', title: 'productname' },
        { field: 'unitcost', title: 'unitcost' },
        { field: 'status', title: 'status' },
        { field: 'listprice', title: 'listprice' },
        { field: 'itemid', title: 'itemid' }
    ]],
    singleSelect: false,
    selectOnCheck: true,
    checkOnSelect: true,
    onLoadSuccess:function(data){                    
        if(data){
            $.each(data.rows, function(index, item){
                if(item.checked){
                    $('#dg').datagrid('checkRow', index);
                }
            });
        }
    }                 
});

重新執行頁面後就可以看到 checked 為 true 的資料列 Checkbox 都為勾選,

image

再來就是要取得勾選的資料值,這邊也是使用 DataGrid 所提供的 Method「getChecked」

image

程式如下:

$('#ButonGetCheck').click(function(){
    var checkedItems = $('#dg').datagrid('getChecked');
    var names = [];
    $.each(checkedItems, function(index, item){
        names.push(item.productname);
    });                
    console.log(names.join(","));
});

最後的執行結果:

image

image

image

方式一的完整 Javascript 程式:

$('#dg').datagrid({
    title: 'CheckBox Selection on DataGrid',
    url: 'datagrid_data3.json',
    width: '700',
    rownumbers: true,
    columns:[[
        { field:'ck',checkbox:true }, 
        { field: 'productid', title: 'productid' },
        { field: 'productname', title: 'productname' },
        { field: 'unitcost', title: 'unitcost' },
        { field: 'status', title: 'status' },
        { field: 'listprice', title: 'listprice' },
        { field: 'itemid', title: 'itemid' }
    ]],
    singleSelect: false,
    selectOnCheck: true,
    checkOnSelect: true,
    onLoadSuccess:function(data){                    
        if(data){
            $.each(data.rows, function(index, item){
                if(item.checked){
                    $('#dg').datagrid('checkRow', index);
                }
            });
        }
    }                 
});
 
$('#ButonGetCheck').click(function(){
    var checkedItems = $('#dg').datagrid('getChecked');
    var names = [];
    $.each(checkedItems, function(index, item){
        names.push(item.productname);
    });                
    console.log(names.join(","));
});

 

設定方式二:不使用預設的設定方式與 Method

這個設定的方式應該是在 jQuery EasyUI 1.3 之前所使用的,因為早期的版本並沒有足夠的設定方式與 Method 讓使用者可以去增加 Checkbox 的項目,這邊所使用的 JSON 資料以及 HTML 原始碼都跟設定方式一的內容是一樣的,不一樣的地方在於 Javascript 程式的部份,

先看 DataGrid 的設定

$('#dg').datagrid({
    title: 'CheckBox Selection on DataGrid',
    url: 'datagrid_data3.json',
    width: '700',
    rownumbers: true,
    columns:[[
        {field:'checked',formatter:function(value,row,index){ 
            if(row.checked){
                return '<input type="checkbox" name="DataGridCheckbox" checked="checked">'; 
            }
            else{
                return '<input type="checkbox" name="DataGridCheckbox">'; 
            }
        }}, 
        { field: 'productid', title: 'productid' },
        { field: 'productname', title: 'productname' },
        { field: 'unitcost', title: 'unitcost' },
        { field: 'status', title: 'status' },
        { field: 'listprice', title: 'listprice' },
        { field: 'itemid', title: 'itemid' }
    ]],
    singleSelect: true
});

這邊的 Checkbox 設定則是使用 formatter 的方式,類似 ASP.NET GridView 的 ItemTemplate 設定方式,判斷每個資料列的 checked 欄位資料是否為 true,如 checked 為 true 則回傳一個有勾選的 Checkbox,不過這樣的設定方式就不會在 DataGrid 的欄位名稱列出現可讓使用者全選的 Checkbox,如需要的話就必須再用其他的方式來做設定,不過這邊就不介紹,

image

接著就是取得有勾選的資料值,因為這裡是使用自己加入 checkbox tag 的方式,所以就無法使用 DataGrid 所提供的 getChecked 方法,而是必須要另外寫程式來處理,可以使用 extend 的方式去擴充 DataGrid 的方法,

程式如下:

$.extend($.fn.datagrid.methods, {
    getChecked: function (jq) {
        var rr = [];
        var rows = jq.datagrid('getRows');
        jq.datagrid('getPanel').find('div.datagrid-cell input:checked').each(function () {
            var index = $(this).parents('tr:first').attr('datagrid-row-index');
            rr.push(rows[index]);
        });
        return rr;
    }
});

這麼一來在取得 DataGrid 的 Checkbox 有勾選的資料值就可以沿用方式一的程式,

$('#ButonGetCheck').click(function(){
    var checkedItems = $('#dg').datagrid('getChecked');
    var names = [];
    $.each(checkedItems, function(index, item){
        names.push(item.productname);
    });                
    console.log(names.join(","));
});

執行結果:

image

image

image

完整 Javascript 程式如下:

$(function(){
    $('#dg').datagrid({
        title: 'CheckBox Selection on DataGrid',
        url: 'datagrid_data3.json',
        width: '700',
        rownumbers: true,
        columns:[[
            {field:'checked',formatter:function(value,row,index){ 
                if(row.checked){
                    return '<input type="checkbox" name="DataGridCheckbox" checked="checked">'; 
                }
                else{
                    return '<input type="checkbox" name="DataGridCheckbox">'; 
                }
            }}, 
            { field: 'productid', title: 'productid' },
            { field: 'productname', title: 'productname' },
            { field: 'unitcost', title: 'unitcost' },
            { field: 'status', title: 'status' },
            { field: 'listprice', title: 'listprice' },
            { field: 'itemid', title: 'itemid' }
        ]],
        singleSelect: true
    });
    
    $('#ButonGetCheck').click(function(){
        var checkedItems = $('#dg').datagrid('getChecked');
        var names = [];
        $.each(checkedItems, function(index, item){
            names.push(item.productname);
        });                
        console.log(names.join(","));
    });
});
 
$.extend($.fn.datagrid.methods, {
    getChecked: function (jq) {
        var rr = [];
        var rows = jq.datagrid('getRows');
        jq.datagrid('getPanel').find('div.datagrid-cell input:checked').each(function () {
            var index = $(this).parents('tr:first').attr('datagrid-row-index');
            rr.push(rows[index]);
        });
        return rr;
    }
});

 

以上

3 則留言:

  1. 為什麼 我用會出現jquery.min.js:5 XMLHttpRequest cannot load file:///C:/Users/USER/Desktop/easyui/demo/aatest/datagrid_data1.json. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. 的錯誤

    回覆刪除
    回覆
    1. Cross origin requests are only supported for protocol ...
      http://goo.gl/oIM2Ay
      https://github.com/mrdoob/three.js/wiki/How-to-run-things-locally
      簡單說... 預設狀態下,這是安全性的防護,不是程式的問題

      刪除

提醒

千萬不要使用 Google Talk (Hangouts) 或 Facebook 及時通訊與我聯繫、提問,因為會掉訊息甚至我是過了好幾天之後才發現到你曾經傳給我訊息過,請多多使用「詢問與建議」(在左邊,就在左邊),另外比較深入的問題討論,或是有牽涉到你實作程式碼的內容,不適合在留言板裡留言討論,請務必使用「詢問與建議」功能(可以夾帶檔案),謝謝。