I am trying to create a hidden form field from a boolean value in my viewModel.
<tbody data-bind="foreach: MediaFiles">
<tr>
<td>
<input type="hidden"
data-bind="attr: { value: MyBool }" />
</td>
</tr>
</tbody>
I need the input's value to be either "true" or "false" based on what's in the view model. Other attributes have been omitted for clarity.
What's the best way to accomplish this with knockout's binding functionality?
You can add both a checked and click binding to an input. However, you would want to return true; from the click handler. This will allow the default action to proceed (the checkbox will be checked/unchecked).
This binding is used to bind the child elements of an object in the specified object's context. This binding can also be nested with other type of bindings such as if and foreach. Syntax with: <binding-object> Parameters. Pass the object which you want to use as context for binding child elements as the parameter.
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.
data-bind="attr: { value: MyBool ? 'true' : 'false' }"
or if MyBool is an observable:
data-bind="attr: { value: MyBool() ? 'true' : 'false' }"
or you could use a computed observable:
MyBool = ko.computed(function(){
return this.someValue() ? 'true' : 'false';
}, this);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With