javascriptjquerykendo-uikendo-dropdown

How to set a default value in a Kendo jquery dropdown based upon a json attribute


I thought this would be super simple, but can't find the solution. I have a Kendo dropdown built using Jquery. I can't work out how to dynamically set the default value based upon an attribute within the Json.

Datasource is this:

var dataStores2 = {"stores":[{"id":100, "name":"Shop 1" ,"defaultStore":false},{"id":150, "name":"Shop 2" ,"defaultStore":true},{"id":900, "name":"Shop 3" ,"defaultStore":false}]};

Dropdown is built using:

 var storeList = $('#StoreNameSelect').data('kendoDropDownList');

              if (!storeList) {
                console.log('store list is not initialised');
                // create DropDownList from input HTML element
                $('#StoreNameSelect').kendoDropDownList({
                  dataTextField: 'name',
                  dataValueField: 'id',
                  dataSource: dataStores2.stores,
                  dataBound: function(e) {
                    // handle the event
                    console.log(this);
                    this.select(1);
                }
                });
              }

You can see I am hard coding the default value in the dataBound event using: this.select(1);

How can I base that dynamically on the defaultStore boolean within the Json?


Solution

  • I am using this as a solution, but would be interested if there is a better way of doing this.

          if (!storeList) {
            console.log('store list is not initialised');
            // create DropDownList from input HTML element
              $('#StoreNameSelect').kendoDropDownList({
                dataTextField: 'name',
                dataValueField: 'id',
                dataSource: dataStores2.stores,
                dataBound: function(e) {
                  // handle the event
                  for (var i=0,len=dataStores2.stores.length; i<len; i++){
                    //console.log(dataStores2.stores[i].defaultStore);
                    if(dataStores2.stores[i].defaultStore){
                      this.select(i);
                    }
                  } 
              }
            });
          }