I’m using version 2.2.0 of KO, and I’m tryign to set the CSS for an option element like so:
<select data-bind="foreach: $data.answers, value: selectedAnswer">
<option data-bind="css: $data.getScoringLevel, value: $data, text: $data.text"></option>
</select>
Here is the getScoringLevel() function:
// Answer.
var Answer = function () {
var self = this;
self.id = '';
self.text = '';
self.sendAnswerToWebService = true;
self.scoringLevel = ko.observable(0);
self.getScoringLevel = ko.computed(function () {
switch (self.scoringLevel()) {
case 1:
return 'red';
case 2:
return 'orange';
case 3:
return 'yellow';
default:
return '';
}
}, self);
};
I can see the function is executed, sicne a breakpoint I place inside of it is hit, but the rendered HTML looks like this:
<option data-bind="css: $data.getScoringLevel, value: $data, text: $data.text" value="">Choose....</option>
There is no class attribute set for some reason. I was expecting, for exmample, `class=”red”‘ somewhere.
Can someone tell me what I’m doing wrong please?
It works. You see such html because default value of
scoringLevelis 0 and your computed returns empty string. If you change it, for example to 1, red class will be assigned to the option.Here is a fiddle: http://jsfiddle.net/vyshniakov/DtDk7/1/