TheWebs
TheWebs

Reputation: 12923

Select the first radio button knockout js

Consider the following:

self.container = ko.observableArray([{name: 'hello', amount: [{item: name, key: '4', selected: 0}, {item: 'name', key: 2, selected: '1'}]}, {name: 'hello', amount: [{item: name, key: 10, selected: 0}, {item: name, key: 8, selected: '1'}]}]);
self.amountSelected = ko.observableArray();

If I do:

<div data-bind="foreach: container">
  <div data-bind="foreach: amount">
    <input type="radio" name="radio-selection-name" data-bind="attr: {value: key}, checked: $root.amountSelected()[$index()] || selected" />
  </div>
</div>

This works, what doesn't work is notice how one of the amounts it's selected as it has a '1'

How do I say, select the currently selected item or use the selected item for this object?

Is there a way to set, for that index, the radio to selected if the selected attribute on the object is a '1'?

Upvotes: 0

Views: 978

Answers (1)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

You cannot select more then one radio, so the checked binding dont need to be an observableArray for radios. The best way to set the value of the input is the checkedValue binding, in the snippet there are an example of both, but plese see the documentation Checked binding KO it is very useful.

function ViewModel(){
  this.container = ko.observableArray([{name: 'hello', amount: [{item: name, key: 4, selected: 0}, {item: 'name', key: 2, selected: '1'}]}, {name: 'hello', amount: [{item: name, key: 10, selected: 0}, {item: name, key: 8, selected: '1'}]}]);
   
   this.amountSelectedRadio = ko.observable(2);
   this.amountSelectedChecked = ko.observableArray([8,4]);  
  
}


ko.applyBindings(new ViewModel())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h2>Checked Binding: Radio</h2>
<div data-bind="foreach: container">
  <div data-bind="foreach: amount">
    <input type="radio" name="radio-selection-name" data-bind="checked: $root.amountSelectedRadio, checkedValue: key" />
  </div>
</div>

<h2>Checked Binding: CheckBox</h2>

<div data-bind="foreach: container">
  <div data-bind="foreach: amount">
    <input type="checkbox" name="checkbox-selection-name" data-bind="checked: $root.amountSelectedChecked, checkedValue: key" />
  </div>
</div>

Upvotes: 1

Related Questions