Conditionally add an element attribute in knockout.js

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 Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)