Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout js conditional options binding

In Knockoutjs is it possible to have a condition for the child elements for a options binding

e.g:

viewModel.array([{name: 1, show: true}, {name: 2, show: false}, {name: 3, show: true}]);

<select data-bind="options: array, optionsText: name, if: show"></select>

will show in select box:

1
3
like image 425
nehz Avatar asked Sep 26 '26 13:09

nehz


2 Answers

Checkout this demo

You can do it like this :

 <select  data-bind="value: selectedCountry , foreach : countryArray" >
       <!-- ko if: show -->        
            <option data-bind="value : name, text : name "></option>
       <!-- /ko -->
 </select> ​

function viewModel() {

    var self = this;
    this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
                                            {"name" : "Italy" , "show" : true},
                                            {"name":"Germany" , "show" : false}]);

    this.selectedCountry = ko.observable("");

}

$(document).ready(function() {

    var vm = new viewModel();
    ko.applyBindings(vm);

})​
like image 170
Luffy Avatar answered Sep 28 '26 04:09

Luffy


Try this demo

Here's a 2017 update: The best way to do this (especially without containerless conditional binding) comes from the knockout documentation for post-processing option bindings, using the optionsAfterRender binding. optionsAfterRender was added in version 2.3

Your code would look like this :

 <select  data-bind="value: selectedCountry , options : countryArray, optionsText: 'name', optionsAfterRender: setOptionsShow" ></select>  ​

function viewModel() {

    var self = this;
    this.countryArray = ko.observableArray([{"name" : "France" ,"show" : true},
                                            {"name" : "Italy" , "show" : true},
                                            {"name":"Germany" , "show" : false}]);

    this.selectedCountry = ko.observable("");
    this.setOptionsShow = function(option, item) {
            ko.applyBindingsToNode(option, {visible: item.show}, item);
        }

}

$(document).ready(function() {

    var vm = new viewModel();
    ko.applyBindings(vm);

})​
like image 34
Gavin Esplin Avatar answered Sep 28 '26 03:09

Gavin Esplin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!