How to correctly bind the boolean value to select

Showing 1-7 of 7 messages
How to correctly bind the boolean value to select greenl 5/8/12 11:22 PM

Hi,

I want to bind boolean value to select element using KO, but obviously it doesn't work as expected.

html code:


<select data-bind="value: state">
   
<option value="true">On</option>
    <option value="false">Off</
option>
</select>

Javascript code:


var model = {
    state
: ko.observable(false)
};

ko
.applyBindings(model)

So I expect the select box goes to "Off" position with the initial value false but it was at "On". If I put state: ko.observable("false") it will be correct but that's not I wanted. Anyone know how to bind the boolean value to select box with KO?

SO: http://stackoverflow.com/questions/10510683/knockoutjs-bind-boolean-value-to-select-box

Fiddle: http://jsfiddle.net/greenlaw110/Ajm58/

thx,
Green

Re: How to correctly bind the boolean value to select mila...@gmail.com 5/9/12 3:19 PM
You have to use the strings 'false' and 'true'.
Re: How to correctly bind the boolean value to select greenl 5/9/12 6:09 PM
That's what I am trying to avoid because my data come from backend is boolean false, not string "false"
Re: How to correctly bind the boolean value to select rpn 5/9/12 7:02 PM
An option that I have used in the past is to create a quick "booleanValue" custom binding that injects a writeable computed observable between your actual observable and the binding.  You could alternatively use a computed observable on your view model, but this binding allows you to avoid any extra clutter on your view model.

Re: How to correctly bind the boolean value to select greenl 5/9/12 7:58 PM
Cool, that's what I need indeed.

A problem is when I run this fiddle, I suppose the select box should be on "Off" option, while it is not actually. Anything run in the code?
Re: How to correctly bind the boolean value to select rpn 5/9/12 8:09 PM
I updated the fiddle.  I think that this is a better version now.   http://jsfiddle.net/rniemeyer/H4gpe/ 
Re: How to correctly bind the boolean value to select greenl 5/9/12 10:27 PM
This is perfect. If you put the answer to SO I will give you credential:  http://stackoverflow.com/questions/10510683/knockoutjs-version-2-1-0-bind-boolean-value-to-select-box