I have 2 select lists and I want to sync the index, so when the first has an index of 1 the second will have an index of 1 etc.
This is my html.
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.2.0/knockout-min.js"></script>
<div>
<select id="selLight" data-bind="options: $root.ddlLight, value: ddlLightSelected"></select>
<select id="selAction" data-bind="options: $root.ddlAction, value: ddlActionSelected"></select>
</div>
and the javascript…
var ViewModel = function() {
var self = this;
self.ddlLight = ko.observableArray(["RED", "AMBER", "GREEN"]);
self.ddlAction = ko.observableArray(["STOP", "READY", "GO"]);
self.ddlLightSelected = ko.observable();
self.ddlActionSelected = ko.observable();
self.ddlLightSelected.subscribe(function (event) {
document.getElementById("selAction").selectedIndex =
self.ddlLight.indexOf(self.ddlLightSelected());
});
self.ddlActionSelected.subscribe(function (event) {
document.getElementById("selLight").selectedIndex =
self.ddlAction.indexOf(self.ddlActionSelected());
});
};
ko.applyBindings(new ViewModel());
I have a fiddle with the exact problem…
http://jsfiddle.net/phykell/2vUTw/
EDIT: I was having a few problems with jsfiddle, so here is a jsbin…
http://jsbin.com/ilomer/4/
…and here’s how to recreate the issue:
- Run the jsFiddle
- Select GREEN from the LIGHTS (ACTIONS will change to GO) 3. Select STOP from the ACTIONS (LIGHTS should change to RED but they don’t)
The problem is this line of code:
You’re directly changing the DOM, not allowing Knockout to kick off the observable pattern.
If you want something to change, always change the
ko.observable, not the JavaScript variable or the DOM. Knockout will recognize the change, and therefor change the DOM itself. The solution would be:Updated JS Bin.