How can I re-check a checkbox in a kendo grid afte

2019-08-05 23:20发布

问题:

I have a checkbox for each row within a kendo grid. If the user sorts or filters the grid, the checkmarks are cleared from the checkboxes. How can I prevent the checkboxes from unchecking or re-check them after the sort or filter occurs? Please refer to the following js fiddle to observe the behavior during sorting:

http://jsfiddle.net/e6shF/33/

Here's the code on the jsfiddle for reference (...needed to ask this question):

$('#grid').kendoGrid({
    dataSource: { data: [{id:3, test:'row check box will unchecked upon sorting'}]},
    sortable: true,
    columns:[
{
    field:'<input id="masterCheck" class="check" type="checkbox" /><label for="masterCheck"></label>', 
    template: '<input id="${id}" type="checkbox" />',
    filterable: false,
    width: 33,
    sortable: false // may want to make this sortable later. will need to build a custom sorter.
},
    {field: 'test',
     sortable: true}
]});

回答1:

basically the selection is cleared each time because the Grid is redrawn. You can store the check items in an array or object and when the Grid is redrawn (dataBound event) you can mark them again as checked.

To simplify things here is an updated version of you code. Also use the headerTemplate option to set header template - do not name your field like template instead.

var array = {};
$('#grid').kendoGrid({
    dataSource: { data: [{id:3, test:'row check box will unchecked upon sorting'}]},
    sortable: true,
    dataBound:function(){
        for(f in array){
            if(array[f]){
                $('#'+f).attr('checked','checked');
            }
        }
    },
    columns:[
    {
        headerTemplate:'<input id="masterCheck" class="check" type="checkbox" /><label for="masterCheck"></label>', 
        template: '<input id="${id}" type="checkbox" />',
        filterable: false,
        width: 33,
        sortable: false // may want to make this sortable later. will need to build a custom sorter.
    },
        {field: 'test',
         sortable: true}
    ]});

var grid = $('#grid').data().kendoGrid;
$('#grid tbody').on('click',':checkbox',function(){   
    var id = grid.dataItem($(this).closest('tr')).id;
    if($(this).is(':checked')){        
        array[id] = true;
    }else{
        array[id] = false;
    }
})

Link to the fiddle



回答2:

If you are not too concerned about old browsers HTML5 storage might work for you http://www.w3schools.com/html/html5_webstorage.asp And of course jQuery comes with its own data storage capability.