Using attr binding in Knockout with a boolean value
Asked Answered
P

1

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?

Platyhelminth answered 3/7, 2012 at 3:18 Comment(0)
D
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);
Deafening answered 3/7, 2012 at 3:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.