Maxcot
Maxcot

Reputation: 1599

How can I get the value AND label on a radio button in knockout.js?

My model holds both a numerical score (numerical value) for each radio option in a group, and also a label (text) for each same radio option.

Think of a survey - the prompted responses to each question vary from question to question.

<td data-bind="foreach: allowed_responses"><input type="radio" data-bind="value: score, checked: $parent.selectedResponse" /><span data-bind="text: label"></span></td>

And then my javascript will give me the numerical value of the selected radio button.

self.getSelectedScores = function() {
....
"score": questions[i].selectedResponse()
....

How would I pickup the the label of the chosen radio button?

Upvotes: 0

Views: 197

Answers (1)

Ray
Ray

Reputation: 3959

By using the checkedValue binding. It takes the entire object as the selected value instead of just the score.

var viewModel = function(){
  var self = this;
  self.allowed_responses = ko.observableArray([
    {
      'score' : 1,
      'label' : 'One'
    },
    {
      'score' : 2, 
      'label': 'Two'
    }
  ]);
  
  self.selectedResponse = ko.observable();
  self.getSelectedScoreandLabel = function(){
    console.log('label: ' + self.selectedResponse().label);
    console.log('value: ' + self.selectedResponse().score);
  };
}

ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: allowed_responses -->
<td>
  <input type="radio" data-bind="value: score, checkedValue: $data, checked: $root.selectedResponse" />
  <span data-bind="text: label"></span>
</td>
<!-- /ko -->
<br>
<br>
<button data-bind="click: getSelectedScoreandLabel">Show response</button>

P.S. foreach doesn't seem to be working with <td>, so I used a virtual element.

Upvotes: 0

Related Questions