Skeeve
Skeeve

Reputation: 1255

Knockout options conditional css

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 a select with options from this array:

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

How with the help of knockout can I make so that if question.personalized == "Y" color of the text of this question would be green?

Upvotes: 5

Views: 4360

Answers (3)

SiMet
SiMet

Reputation: 612

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

It's not the best option (the best is to set new class) but it's possible

Upvotes: 1

Alexandros B
Alexandros B

Reputation: 1891

Your best bet is the css binding

A quick adaptation of the documentation to your need would 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>

Upvotes: 4

demkalkov
demkalkov

Reputation: 511

You can use foreach instead of usual options binding. Something like

<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>

Upvotes: 3

Related Questions