How to correctly bind the boolean value to select

14,922 views
Skip to first unread message

green

unread,
May 9, 2012, 2:22:31 AM5/9/12
to KnockoutJS

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

mila...@gmail.com

unread,
May 9, 2012, 6:19:38 PM5/9/12
to knock...@googlegroups.com
You have to use the strings 'false' and 'true'.

green

unread,
May 9, 2012, 9:09:13 PM5/9/12
to knock...@googlegroups.com
That's what I am trying to avoid because my data come from backend is boolean false, not string "false"

rpn

unread,
May 9, 2012, 10:02:07 PM5/9/12
to knock...@googlegroups.com
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.

green

unread,
May 9, 2012, 10:58:17 PM5/9/12
to knock...@googlegroups.com
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?

rpn

unread,
May 9, 2012, 11:09:51 PM5/9/12
to knock...@googlegroups.com
I updated the fiddle.  I think that this is a better version now.   http://jsfiddle.net/rniemeyer/H4gpe/ 

green

unread,
May 10, 2012, 1:27:08 AM5/10/12
to knock...@googlegroups.com
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 
Reply all
Reply to author
Forward
0 new messages