Multirow select only returning first row of grid

3 posts, 0 answers
  1. Andy
    Andy avatar
    22 posts
    Member since:
    Feb 2016

    Posted 20 Apr 2016 Link to this post

    My grid has "selectable: "row multiple"" set, and I want to make copies of all selected rows when a "Copy" custom button is pressed.

    Please take a look at my code so far:

    $('a.k-grid-copy').click(function (e) {
        e.preventDefault();
        var grid = $("#grid").data("kendoGrid");
        grid.select().each(function () {
            console.log(this);
            var selected = grid.dataItem(this);
            console.log(selected);
            grid.dataSource.add({
                a: selected.a,
                b: selected.b,
                c: selected.c
            });
                        
        });
    });

    When I console.log(this) in the body of the .each() function, the rows are logged correctly. However, grid.dataItem(this) will return the first selected row in the first loop iteration, then for all subsequent iterations, it will return the first row of the grid (whether or not it is selected). Why is this happening? As I stated above, this for each iteration is CORRECT, but when you set var selected to grid.dataItem(this), selected becomes the first selected row on the first iteration in .each(), then it becomes the first row in the grid on all subsequent iterations.

    Here is a Dojo that recreates the problem: http://dojo.telerik.com/ApAJU

    The issue only appears when selecting multiple rows. Try selecting any number of rows > 1, press the Copy button, and see the console. The <tr> elements are correct, but the JS objects are not. This does not happen when you do not add the rows after (a.k.a if you ONLY log and do not create copies, there is no problem). Thus, there is something wrong with adding the copies.

    Thanks

    Andy

  2. Andy
    Andy avatar
    22 posts
    Member since:
    Feb 2016

    Posted 20 Apr 2016 in reply to Andy Link to this post

    I ended up finding a workaround where I store all the copied rows in an array during the .each(), and then re-loop through that array and add each row to the dataSource. 

    However, if you could still provide an explanation as to why this behaviour occurred, that would be great.

  3. Dimiter Madjarov
    Admin
    Dimiter Madjarov avatar
    2310 posts

    Posted 22 Apr 2016 Link to this post

    Hello Andy,

    The reason for this behavior is the invocation of grid.dataSource.add() in the loop. Modifying the dataSource will redraw the Grid table according to the new dataItems, so the selection is not existing after the first iteration.

    Regards,
    Dimiter Madjarov
    Telerik
     
    Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
     
Back to Top