Binding a numeric field to input and receiving a number, not a string

2,598 views
Skip to first unread message

Nilesh Trivedi

unread,
Jul 5, 2013, 5:51:54 PM7/5/13
to knock...@googlegroups.com
Hi,

I have a numeric field in my model which I have bound to a HTML5 number input field using:

<input type="number" data-bind="value: age"/>

Reading from the model works fine. However, when the user changes the value in the input field, the age property is set with a string value, not a number.

In Chromium 25.0, which supports HTML5 Number input fields, invalid input values such as "foobar" are set as a blank string "" and numbers like 54 are set as the string "54".
In Firefox 21.0, which does not support Number input fields, all strings are accepted and set in the model.

The Control Types example on KnockOut website ( http://knockoutjs.com/examples/controlTypes.html ) does not show any example of a numeric field which is what I am looking for.

What's the best way for me to ensure that input is validated properly and then set in the model as a number, not a string?

cheers
nilesh

Nilesh Trivedi

unread,
Jul 5, 2013, 6:12:45 PM7/5/13
to knock...@googlegroups.com
Replying to myself but I just found this example of forcing input to be numeric using extenders which works for me:

http://knockoutjs.com/documentation/extenders.html

cheers
nilesh

Uğur Tılıkoğlu

unread,
Jul 8, 2013, 12:44:18 AM7/8/13
to knock...@googlegroups.com
you can also write a custom binding handler like at http://jsfiddle.net/tilikoglu/HksnV/




cheers
nilesh

--
You received this message because you are subscribed to the Google Groups "KnockoutJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knockoutjs+...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Nilesh Trivedi

unread,
Jul 11, 2013, 11:24:50 PM7/11/13
to knock...@googlegroups.com
Thanks. I modified your jsFiddle to be able to run without jQuery: http://jsfiddle.net/vegGz/1/

cheers
nilesh

Uğur Tılıkoğlu

unread,
Jul 12, 2013, 3:56:17 AM7/12/13
to knock...@googlegroups.com
thanks, it looks better now..
Reply all
Reply to author
Forward
0 new messages