Link to home
Start Free TrialLog in
Avatar of ccravenbartle
ccravenbartle

asked on

Knockout JS CSS binding

I am trying knockout css binding for the first time...  In a table, I want to set the Status element label to the Bootstrap class 'label-success' or 'label-important' based on the string value returned by the observable Status()  

<tbody data-bind="foreach: PurchaseRequests" >
        <tr>
            <td data-bind="text: Date"></td>
            <td data-bind="text: Reference"></td>
             <td>
                    <span data-bind="text: Status, 
                     css: {'label' :  true,
                             'label-success' :  Status() == 'Draft',
                             'label-important': Status() == 'Approved'}">
                    </span>
            </td>
         </tr>
         </tbody>

Open in new window


However, at runtime I get a:  JavaScript runtime error: Function expected

Is it even possible to do css binding on strings or does it expect to evaluate boolean or numeric values?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

What about :
<span data-bind="text: Status, 
                     css: {'label' :  true,
                             'label-success' :  DraftStatus(),
                             'label-important': ApprovedStatus() }">

Open in new window

And :
self.DraftStatus = ko.observable(false); // class Draft will be not set by default
self.ApprovedStatus = ko.observable(true); // class Approved will be set by default

Open in new window

Avatar of ccravenbartle
ccravenbartle

ASKER

Leakim: thank you for your response.  However, I'm not sure how to get this to work as Status() is a string and can be 'Draft', 'Sent For Approval', 'Approved' or 'Posted'.   I imagine I would need a new observable for each.  The PurchaseRequests observable array is being created via the Ajax call below.  Would I need loop through each element of the observable array to set up these new observables for each Purchase Request?

vm.PurchaseRequests.getPurchaseRequests = function () {
            $.ajax({
                url: '@Url.Action("GetOutstandingRequest", "ControlPanel")',
                type: 'GET',
                contentType: 'application/json',
                dataType: 'json',
                success: function (result) { vm.PurchaseRequests(result); }
            });
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Leakim: Thank you - your approach worked