Css conditional knockout options

I have an observable array of objects

question = {
        ownerUserName: item.id,
        text: item.text,
        dataType: item.dataType,
        personalized: item.personalized,
        status: item.status,
        actionUserName: item.actionUserName
    }

And select options from this array:

<select id="questId" style="width: 425px" data-bind="options: questionList, optionsText: 'text'">

How can I make a knockout so that if question.personalized == "Y" the text color of this question is green?

+5
source share
3 answers

Best css binding

Quickly adapting documentation to your needs will be

<div data-bind="text: personalized, css: personalizedStatus">
   Profit Information
</div>

<script type="text/javascript">
    question.personalizedStatus = ko.computed(function() {
        return this.personalized() == "Y" ? "green" : "red";
    }, question);

</script>
<style>
    .green {color:green;}
    .red{color:red;}
</style>
+4
source

You can use foreach instead of the usual options . Sort of

<style>
   .highlighted{
      background-color: red;
   }
</style
<select id="questId" style="width: 425px" data-bind="foreach: questionList">
   <option data-bind="text: text, class: {highlighted: personalized == 'Y'}">
</select>
+3
source

There is also an option to set data-bind = "style: {color: value? 'Green': null}"

This is not the best option (it’s best to install a new class), but it’s possible

+1
source

All Articles