Conditionally add an element attribute in knockout.js

The knockout.js library has an "attr" data binding which allows you to dynamically change the value of an HTML element attribute (e.g. the “title”). However, in some cases, the attribute may or may not be needed depending on the corresponding observable on the bound object. For example, if my model has a “title” observable I might want to set the “title” attribute if it is present (non-null) or skip the attribute entirely if it is not present (null).

Does knockout provide any way to conditionally set an attribute? (Ideally without conditionally rendering the entire element opening tag…)

[Note] This similarly named question was actually resolved by knockout’s special handling of CSS classes and does not relate to this question (or its own title): How to conditionally render an css class with knockoutjs

Answer

I needed this when selecting an <option> (that I was generating manually instead of built-in knockout).

<option 
 data-bind="text: text, 
    attr:{
     value:value,
     'selected': typeof(selected) !== 'undefined' ? selected : null 
     }">
 Choice X
</option>

This says to always update the ‘text’ attribute and to add the ‘value’ attribute, but only add ‘selected’ if the the data already has a value of ‘selected’ defined.

Leave a Reply

Your email address will not be published. Required fields are marked *