Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockoutjs support for multiple groups (aka: name attribute) in the radio binding

Tags:

knockout.js

I am having problems trying to generate dynamic radio button groups, grouping them by the name attribute. KO is generating the names using the following format: "ko_unique_{0}" and it is not using the binding I am setting.

Any idea how to solve this?

Many thanks!

Given the following vm:

vm = {
  questions: [{ id: "q1", question: "first question", answer: "y" },
                   { id: "q2", question: "second question", answer: "n" }],
  answerOptions: [{ key: "y", value: "Yes" },
                           { key: "n", value: "No"}]
};

and the following markup:

<ol data-bind="foreach: questions">
  <li>
    <span data-bind="text: question"></span>
    <span data-bind="foreach: $parent.answerOptions">
      <span data-bind="text: value"></span><input type="radio" data-bind="value: key, name: $parent.id, checked: $parent.answer" />
    </span>
  </li>          
</ol>

this is the current output (name attributes with ko_unique_1, ko_unique_2, ko_unique_3 and ko_unique_4 values instead of q1, q1, q2 and q2):

<ol data-bind="foreach: questions">
  <li>
    <span data-bind="text: question">first question</span>
    <span data-bind="foreach: $parent.answerOptions">
      <span data-bind="text: value">Yes</span><input type="radio" data-bind="value: key, name: $parent.id, checked: $parent.answer" name="ko_unique_1" value="y">
      <span data-bind="text: value">No</span><input type="radio" data-bind="value: key, name: $parent.id, checked: $parent.answer" name="ko_unique_2" value="n">
    </span>
  </li>          
  <li>
    <span data-bind="text: question">second question</span>
    <span data-bind="foreach: $parent.answerOptions">
      <span data-bind="text: value">Yes</span><input type="radio" data-bind="value: key, name: $parent.id, checked: $parent.answer" name="ko_unique_3" value="y">
      <span data-bind="text: value">No</span><input type="radio" data-bind="value: key, name: $parent.id, checked: $parent.answer" name="ko_unique_4" value="n">
    </span>
  </li>          
</ol>
like image 781
Jorge Fioranelli Avatar asked Dec 16 '22 03:12

Jorge Fioranelli


1 Answers

You can't set the input's name like that. You have to set it using attr like this:

attr : {name: $parent.id}

Here's a working jsfiddle example for you: http://jsfiddle.net/AJZcw/

like image 86
soniiic Avatar answered May 23 '23 03:05

soniiic