How to create dependent select.
<select class="form-control" id="tf" name="tf" data-bind="value: tf">
<option value="st">Standart</option>
<option value="ht">High</option>
</select>
<select class="form-control" id="tt" name="tt" data-bind="value:tt">
.....
</select>
if one select value == st, show the following values:
<option>75</option>
<option>85</option>
if one select value == ht, show:
<option>100</option>
<option>120</option>
I went with a filtered array for the second select option. run the snippet below.
(I show them all if you did not pick the first select but you can change that behavior if that is not what you want)
function vm() {
var self = this;
this.tfOptions = ko.observableArray([{
'name': 'Standart',
'value': 'st'
}, {
'name': 'High',
'value': 'ht'
}]);
this.tf = ko.observable('');
this.optionsTwo = ko.observableArray([{
'tf': 'st',
'value': '75'
},
{
'tf': 'st',
'value': '85'
},
{
'tf': 'ht',
'value': '100'
},
{
'tf': 'ht',
'value': '120'
}
]);
this.selectedOptionTwo = ko.observable('');
this.filteredoptionsTwo = ko.computed(function() {
var filter = this.tf();
if (!filter) {
return null;
} else {
return ko.utils.arrayFilter(this.optionsTwo(), function(item) {
return item.tf === filter.value;
});
}
}, this);
}
var mymodel = new vm();
$(document).ready(function() {
ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> Options 1: <select class="form-control" id="tf" name="tf" data-bind="options: tfOptions,
optionsText: 'name',
value: tf,
optionsCaption: 'Choose...'">
</select> Options2: <select class="form-control" data-bind="options: filteredoptionsTwo,
optionsText: 'value',
value: selectedOptionTwo
optionsCaption: 'Choose...'"></select>
<p data-bind="with: tf">
for Select One You have selected: <span data-bind="text: name"> </span>,
<span data-bind="text: value"> </span></p>
<p data-bind="with: selectedOptionTwo">
for Select Two You have selected: <span data-bind="text: value"> </span>,
</p>