This is a migrated thread and some comments may be shown as answers.

ListView + Selection

7 Answers 1211 Views
ListView
This is a migrated thread and some comments may be shown as answers.
Ashleigh L
Top achievements
Rank 1
Ashleigh L asked on 12 Jan 2016, 06:02 PM

I want to use the ListView to select items, very similar to this example: http://demos.telerik.com/kendo-ui/listview/selection

There are two items that I'm having a problem with. First, I need to be able to select the first item in the list view by default (ie. on new object creation). I found this code in another thread, but it's not working:

var listView = $("#listView").data("kendoListView");   
listView.select(listView.element.children().first());

Secondly, I need to be able to select an item in the list view by ID (ie. editing an existing object).

This is the JSON I'm sending to the ListView:

{"Icons":[{"Name":"fa-icon-bolt","ID":23},{"Name":"fa-icon-book","ID":3},{"Name":"fa-icon-building","ID"
:32},{"Name":"fa-icon-building-o","ID":24},{"Name":"fa-icon-calculator","ID":15},{"Name":"fa-icon-car"
,"ID":18},{"Name":"fa-icon-certificate","ID":2},{"Name":"fa-icon-cloud","ID":6},{"Name":"fa-icon-cog"
,"ID":33},{"Name":"fa-icon-desktop","ID":4},{"Name":"fa-icon-diamond","ID":26},{"Name":"fa-icon-exclamation"
,"ID":29},{"Name":"fa-icon-file","ID":25},{"Name":"fa-icon-fire-extinguisher","ID":36},{"Name":"fa-icon-flask"
,"ID":16},{"Name":"fa-icon-globe","ID":11},{"Name":"fa-icon-graduation-cap","ID":1},{"Name":"fa-icon-h-square"
,"ID":20},{"Name":"fa-icon-headphones","ID":12},{"Name":"fa-icon-info","ID":27},{"Name":"fa-icon-laptop"
,"ID":8},{"Name":"fa-icon-line-chart","ID":19},{"Name":"fa-icon-mobile","ID":9},{"Name":"fa-icon-newspaper-o"
,"ID":10},{"Name":"fa-icon-plus","ID":28},{"Name":"fa-icon-puzzle-piece","ID":13},{"Name":"fa-icon-road"
,"ID":34},{"Name":"fa-icon-rocket","ID":35},{"Name":"fa-icon-share-square-o","ID":5},{"Name":"fa-icon-suitcase"
,"ID":30},{"Name":"fa-icon-truck","ID":14},{"Name":"fa-icon-university","ID":7},{"Name":"fa-icon-user"
,"ID":22},{"Name":"fa-icon-user-secret","ID":17},{"Name":"fa-icon-users","ID":21}]}

And this is how I'm currently initializing it:

function initIconsView() {
    var datasource = new kendo.data.DataSource({
        transport: {
            read: {
                type: "GET",
                url: "/Controllers/MainController.cfc?method=getIcons",
                processData: true,
                dataType: "json",
                cache: false
            }
        },
        schema : {
            type: "json",
            data: "Icons"
        }
    });
          
    $("#icons_list").kendoListView({
        dataSource: datasource,
        selectable: true,
        template: kendo.template($("#icon_list_template").html())
    });
}

And the template/HTML:

<script id="icon_list_template" type="text/x-kendo-template">
    <div class="icon">
        <i class="#: data.Name # fa-icon-2x"></i>
    </div>
</script>
 
<div class="demo-section k-content wide">
    <div id="icons_list"></div>
</div>

Really they're two different facets of the same issue - programmatically selecting an item in the ListView.

7 Answers, 1 is accepted

Sort by
0
Dimiter Topalov
Telerik team
answered on 14 Jan 2016, 04:17 PM
Hi Shimmoril,

This dojo is based on the mentioned example, and is enhanced with desired functionalities - selecting the first item as a default programmatically (as described in our documentation), and selecting an item by ID using a custom function.

The first one is attached to the dataBound event of the ListView and fires when the data is loaded.

The second functionality provides item selection by given ID of the data item. It relies on obtaining the Uid of the item (coming from the data model) and using it in a jQuery selector in order to get a jQuery object that can be passed to the ListView .select() method.

I hope this helps.

Regards,
Dimiter Topalov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Ashleigh L
Top achievements
Rank 1
answered on 14 Jan 2016, 05:11 PM

Thank you for the examples, they were very helpful. However, I need to combine them.

Basically, I'm setting up a form where users can create and edit pages, and each page is associated w/ an icon. So, if the user is creating a new page, we'll select an icon for them by default (ie. the first one). If they're editing a page, we need to select the icon they've previously chosen and saved in the DB (by ID).

I've done this using your examples, like so:

function initIconsView() {
    var datasource = new kendo.data.DataSource({
        transport: {
            read: {
                type: "GET",
                url: "/Controllers/MainController.cfc?method=getIcons",
                processData: true,
                dataType: "json",
                cache: false
            }
        },
        schema : {
            type: "json",
            data: "Icons"
        }
    });
          
    $("#icons_list").kendoListView({
        dataSource: datasource,
        selectable: true,
        dataBound: selectIcon,
        template: kendo.template($("#icon_list_template").html())
    });
}
         
function selectIcon(e) {
    if (page_id == 0) {
        //if a new page, automatically select the first icon in the display
        var listView = e.sender;
        listView.select(listView.element.children().first());
    }
    else
        //exising page, select the saved icon
        var listView = e.sender;
        var itemWithID = listView.dataSource.data().find(function(item){
            return item.ID === icon_id;
        });
                     
        listView.select(listView.element.children('[data-uid="' + itemWithID.uid + '"]').first());
    }              
}

But I'm getting a javascript error when loading an existing page (new pages work perfectly):

TypeError: itemWithID is undefined
 listView.select(listView.element.children('[data-uid="' + itemWithID.uid + '"]')...

I'm guessing it's due to differences in how my JSON is structured vs the example? I've verified that the icon_id being used in selectIcon is set correctly, and that the item w/ that ID exists in the list view.

0
Ashleigh L
Top achievements
Rank 1
answered on 14 Jan 2016, 06:02 PM

I'm also having trouble assigning the selected item ID to a global variable, for saving the page. I've added the change code:

$("#icons_list").kendoListView({
    dataSource: datasource,
    selectable: true,
    template: kendo.template($("#icon_list_template").html()),
    dataBound: defaultIcon,
    change: function() {
        var data = datasource.view(),
             
        selected_icon_id = $.map(this.select(), function(item) {
            return data[$(item).index()].ID;
        }); alert(selected_icon_id);
    }              
});

But while the selected_icon_id alerts properly right after the change, the value is showing as 0 (the default) when I try to alert it in my save function. I would prefer to get the selected icon ID in the save function, rather than on the list view change, but I couldn't find any examples that worked like that. 

0
Dimiter Topalov
Telerik team
answered on 19 Jan 2016, 08:07 AM
Hello Shimmoril,

The array.find() function returns undefined if no element in the array satisfies the provided testing function. Therefore, based on the provided code, there are three possible reasons itemWithID to be undefined (i.e. .find() doesn't match any elements based on the provided condition):

var itemWithID = listView.dataSource.data().find(function(item){
    return item.ID === icon_id;
});

1) icon_id is undefined - I can not see it being initialized anywhere in the provided code.

2) the data items don't have an "ID" property

3) there are no items with an ID, matching the icon_id (if it's not undefined).

Please make sure that both item.ID and icon_id are not undefined when the code execution reaches the function in question:

var itemWithID = listView.dataSource.data().find(function(item){
console.log(item.ID, icon_id);
    return item.ID === icon_id;
});


As for the assigning the selected item ID to a global variable, you have to make sure nothing overwrites the value set in the change function.

If selected_icon_id is really a global variable (as it seems to be), and there are no scope-related issues, the only way to change the value is to assign a new one explicitly.

If you are still experiencing troubles, please send us a more detailed code sample, containing the current ones plus the following:

- a sample of your data JSON with several items
- your save() function
- the declaration and initialization of all variables involved

Regards,
Dimiter Topalov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Ashleigh L
Top achievements
Rank 1
answered on 19 Jan 2016, 04:27 PM

I figured out the undefined issue - when I was assigning the retrieved data to a javascript variable (icon_id), it was being set as a string, instead of an integer. Thanks for helping me work through that.

For getting the selected_icon_id, it is a global variable, and it's set to 0 when initialized. I then set it in the change function, and alert it at that point, and the value is correct. Then when I hit save on the page, I alert it again, before any of the actual save functionality, and it's 0 again, somehow. I'm not using the variable anywhere else in the code.

I've re-purposed your dojo to show this: http://dojo.telerik.com/OKErI/5

You can see it alert the default selection, alert the new ID when the selection is changed, and alert 0 when the Save button is clicked.

0
Dimiter Topalov
Telerik team
answered on 21 Jan 2016, 02:28 PM
Hi shimmoril,

The described problem occurs because of the comma (,) used for separating the variables in the change event handler:

...
var data = dataSource.view(),
selected_icon_id = $.map(this.select()...
...
 
The above is equivalent to the following, which will hide the selected_icon_id variable in the global scope and use a different one:

var data = dataSource.view();
var selected_icon_id = map...;

Please replace the comma with a semi-color (;)

Regards,
Dimiter Topalov
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Ashleigh L
Top achievements
Rank 1
answered on 21 Jan 2016, 03:30 PM
Ah, yep that'd do it. Completely overlooked that, thanks Dimiter.
Tags
ListView
Asked by
Ashleigh L
Top achievements
Rank 1
Answers by
Dimiter Topalov
Telerik team
Ashleigh L
Top achievements
Rank 1
Share this question
or