Reputation: 13
I'm using knockout in my code and there's a foreach loop in which there are several radio buttons, I'm accessing the first button by $index property. I want this first radio button to be checked by default on load. but there's also a "checked" data-binding with an attribute.
following is the code snippet:
<input type="radio" checked='checked' name="foo" data-bind="value: $data.methodId, checked: $parent.checkout.valueImp">
the radio button doesn't get checked by default. Is there a way by which I can by default put this radio button as 'checked' on load and simultaneously the data-bind also works.
Upvotes: 0
Views: 626
Reputation: 1075139
the radio button doesn't get checked by default
That's because you've bound its checked state to a viewmodel property. To make it checked by default, give $parent.checkout.valueImp
the value of this radio button by default.
Example:
var vm = {
value1: ko.observable("one"),
value2: ko.observable("two"),
currentValue: ko.observable("two") // <===
};
ko.applyBindings(vm, document.getElementById("container"));
Note that Two is checked by default:
<div id="container">
<label>
<input type="radio" name="x" data-bind="value: value1, checked: currentValue"> One
</label>
<br>
<label>
<input type="radio" name="x" data-bind="value: value2, checked: currentValue"> Two
</label>
<div>Curent value: <span data-bind="text: currentValue"></span></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
Upvotes: 0