10

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?

rboarman
  • 8,248
  • 8
  • 57
  • 87

1 Answers1

18
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);
Josh
  • 44,706
  • 7
  • 102
  • 124