Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally render a css class with knockoutjs

Tags:

I have some html like the following:

<div class="control-group">     <input type="text" data-bind="value: $data.DealCode" name="DealCode" class="input-mini" /> </div> 

However, ifnot: $data.DealCodeIsValid, I need to render the following:

<div class="control-group error">     <input type="text" data-bind="value: $data.DealCode" name="DealCode" class="input-mini" /> </div> 

Note the additional class "error" in the div. Is there a way to do that with knockoutjs?

like image 669
devlife Avatar asked Jun 13 '12 11:06

devlife


People also ask

How do I bind a CSS class in angular 6?

Class binding with Class There are another shorthand way to bind CSS Class to HTML element. className is name of the class, which you want to bind to. condition must return true or false. A return value of true adds the class and a false removes the class.

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you bind a class in HTML?

The class binding syntax is also like property binding. In property binding, we only specify the element between brackets. But in the case of class binding, it starts with the prefix class, followed by a dot (.), and the name of the class. You then bind the class value with CSS class name like class.


1 Answers

Something like

<div data-bind="css: {'control-group': true, error: (!$data.DealCodeIsValid)}"> 

Check here for more info

like image 65
jon Avatar answered Sep 19 '22 16:09

jon