Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout attr binding with attributes like 'readonly' and 'disabled'

What's the suggested "best practice" way to use Knockout's "attr" data binding with standalone attributes like "readonly" and "disabled"?

These attributes are special in that they are generally enabled by setting the attribute value to the attribute name (although many browsers work fine if you simply include the attribute names without any values in the HTML):

<input type="text" readonly="readonly" disabled="disabled" value="foo" /> 

However, if you don't want these attributes to be applied, the general practice is to simply omit them altogether from the HTML (as opposed to doing something like readonly="false"):

<input type="text" value="foo" /> 

Knockout's "attr" data binding doesn't support this scenario. As soon as I provide an attribute name, I need to provide a value as well:

<input type="text" data-bind="attr: { 'disabled': getDisabledState() }" /> 

Is there a cross-browser way turn off 'disabled' or 'readonly'? Or is there a trick with a custom binding that I can use to not render anything if I don't want the item disabled or made read-only?

like image 611
Armchair Bronco Avatar asked Jan 04 '13 21:01

Armchair Bronco


People also ask

How do you bind data in knockout JS?

Binding syntaxThe binding name should generally match a registered binding (either built-in or custom) or be a parameter for another binding. If the name matches neither of those, Knockout will ignore it (without any error or warning). So if a binding doesn't appear to work, first check that the name is correct.

What is two-way binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.

What is data bind in HTML?

A data binding connects data from a custom element (the host element) to a property or attribute of an element in its local DOM (the child or target element). The host element data can be a property or sub-property represented by a data path, or data generated based on one or more paths.


1 Answers

Knockout's "attr" data binding does support this scenario just return null or undefined from your getDisabledState() function then it won't emit the attribute.

Demo Fiddle.

like image 80
nemesv Avatar answered Oct 02 '22 16:10

nemesv