check JSFiddle
<div data-bind="foreach: ids" class="">
<label>
<input type="radio" name="someid" data-bind="value: value, checked: $root.selectedid" />
<span data-bind="text: text"></span>
</label>
</div>
<br/>
<input type="button" data-bind="click: test1" value="Test1"/>
<input type="button" data-bind="click: test2" value="Test2"/>
<input type="button" data-bind="click: test3" value="Test3"/>
function radiodata(text,value){ this.text = text; this.value= value; }
var viewModel = function(){
var self = this;
self.selectedid = ko.observable();
self.ids = ko.observableArray([
new radiodata('one',1),
new radiodata('two',2),
new radiodata('three',3)
]);
self.test1 = function(){
self.selectedid(2);//this doesnot work
};
self.test2 = function(){
self.selectedid('2');//this works
};
self.test3 = function(){
self.selectedid((3).toString());//this was my hack
};
}
var model = new viewModel();
ko.applyBindings(model);
I was trying to radio databind
for checked
property,
My json data for selectedid
is integer which I was trying to bind checked
for radio.
I have patched solution for that too, but does anyone know why integer databind is not working?
like, where self.testX
functions will change the radio checked
property
self.test1 = function(){
self.selectedid(2); //this doesnot work
};
self.test2 = function(){
self.selectedid('2');//this works
};
self.test3 = function(){
self.selectedid((3).toString()); //and this was my hack
};
any good explanation ?
You need to also use the checkedValue
binding if you want the checked
binding to use something else than the value string of the element for selection. From the knockout documentation on the checked binding:
If your binding also includes checkedValue, this defines the value used by the checked binding instead of the element’s value attribute. This is useful if you want the value to be something other than a string (such as an integer or object), or you want the value set dynamically.
If you look at the documentation you'll also see a sample where they use the current $data
object as checkedValue
.
Edit: Adding explanation why converting the value to a string helped in the question.
The reason the selection worked fine if you converted the integer to a string is that the checked binding does the comparison for equality without allowing type conversions, i.e. uses ===
instead of ==
for equality comparison.
An example of this is:
1 == "1" // true
1 === "1" // false
In the first line in the sample above, JavaScript makes a type conversion when performing the comparison (which makes the operands on both sides of the comparison operator the same type), while in the latter it does not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With