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
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);
})
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);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With