Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attr binding in knockout with a boolean attribute 'autofocus'

For some attributes, it is the presence of the attribute that has an effect - the value that is assigned to it is irrelevant. For example, the autofocus attribute can be set to 'false' or 'true, or 'banana' and the element is still gets automatically focused. IE, the following are all equivalent and cause the div to get focus :

<div autofocus="false" contenteditable="true"></div>
<div autofocus="true" contenteditable="true"></div>
<div autofocus="banana" contenteditable="true"></div>

Knockout has an 'attr' binding, but it seems to be only useful for assigning values to attributes, not for adding/removing attributes.

Is there another way to do it in knockout, or am I forced to set it from javascript?

NB Using chrome on ubuntu.

like image 976
Max Waterman Avatar asked Aug 16 '12 14:08

Max Waterman


1 Answers

Use a boolean false value to remove the attribute, use a string 'false' to set the attribute. What more do you need?

eg:

// Set as boolean, removes the attribute
autofocus(false);   

// Set as boolean, adds the attribute
autofocus(true);  

// Set as string, adds the attribute
autofocus('false');   

// Set as string, adds the attribute
autofocus('true');   

See here for an example: http://jsfiddle.net/badsyntax/XMDFh/

like image 154
badsyntax Avatar answered Oct 28 '22 05:10

badsyntax