Knockoutjs support for multiple groups (aka: name attribute) linked to the radio

I'm having trouble creating dynamic switch groups by grouping them by the name attribute. KO generates names using the following format: "ko_unique_ {0}" and does not use the binding that I set.

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 values ​​ko_unique_1, ko_unique_2, ko_unique_3 and ko_unique_4 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> 
+4
source share
2 answers

You cannot set such input to name . You must install it with attr as follows:

 attr : {name: $parent.id} 

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

+11
source

Alternatively, you can do this with jQuery.

 $('input').setAttribute('name', $parent.id); 

especially if you are registering a new component, you can do this in the createViewModel function

0
source

Source: https://habr.com/ru/post/1398558/


All Articles