How can I set default selects in multiple select with foreach binding

41 views
Skip to first unread message

h...@homemaster.co.kr

unread,
Aug 22, 2017, 5:08:40 AM8/22/17
to KnockoutJS
Hello I'm trying to make default selected  multiple binding in for loop
I have following situation. 
company have  productList and managerList 
each  manager has their own  prefered_products with in company's product list. 
I want to  show this data in table. I want to make show prefered_product of manager and other products of company  
html file
 <tbody data-bind="foreach: Managers">
      <tr >       
        <td class="col-xs-2">
                                <select type="text" data-bind="options:$parent.productList,optionsText:'name', selectedOptions:prefered_products'" class="form-control" ></select>
       </td>
 </tr>


js file
var products = [ {name: 'product1', _id : 'abc'},{name: 'product2', _id : 'def'},{name: 'product3', _id : 'ghi'}]
var managers = [ {_id : 'mand', name: 'kate', prefered_products: [{name: 'product2', _id : 'def'},{name: 'product3', _id : 'ghi'}] },
                            {_id : 'todhm', name: 'jordan', prefered_products: [{name: 'product1', _id : 'abc'},{name: 'product2', _id : 'def'}]}]
var ManagerData =function(data){
        var self = this
        self.id = ko.observable(data._id);
        self.name = ko.observable(data.name);
        self.prefered_products = ko.observableArray([]);
        self.add_product = function(product){
                self.prefered_products.push(new Product(product));
        }
        for(i=0; i< data.prefered_products.length;i++){
            self.add_product(data.prefered_products[i]);
        }
}

var ProductType = function(data){
        var self = this;
        self.name = ko.observable(data.name);
        self._id = ko.observable(data._id);
}

var ViewModel = function(){
       self.productList = ko.observableArray([]);
       self.managerList = ko.observableArray([]);
}
var ViewModel = new ViewModel();
 ko.applyBindings(ViewModel);
 products.forEach(function(product,index){
                           ViewModel.productList.push(new Product(product));
                       })
managers.forEach(function(manager,indexdo){
                          ViewModel.ManagerList.push(new ManagerData(manager));
                                     }

noirabys

unread,
Aug 24, 2017, 3:11:00 AM8/24/17
to KnockoutJS
hi,
the context is based on the object you supply with applyBindings.
there is neither a Managers object in your viewmodel nor a global variable.
-> foreach: managerList 

best regards,
 noirabys
Reply all
Reply to author
Forward
0 new messages