Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using attr binding in Knockout with a boolean value

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?

like image 789
rboarman Avatar asked Jul 03 '12 03:07

rboarman


People also ask

How to bind checkbox in Knockout?

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).

What is binding in knockout?

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.

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.


1 Answers

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);
like image 175
Josh Avatar answered Sep 18 '22 07:09

Josh