Warm tip: This article is reproduced from stackoverflow.com, please click
asp.net html knockout.js

How to bind name attribute of a radio button in knockout

发布于 2020-04-21 22:00:34

I have this code in my ASP.Net project which is using knockout.js:

<div>
     <input type="radio" name="hearingAidConditionGroup" value="Yes" data-bind="checked: condition">&nbsp;<label class="YesNo">&nbsp;Yes&nbsp;</label>
     <input type="radio" name="hearingAidConditionGroup" value="No" data-bind="checked: condition">&nbsp;<label class="YesNo">&nbsp;No&nbsp;</label>
</div>

which is stored in a file called a.cshtml, I have another html file which includes this one like:

<div data-bind="with: testConditions()[0]">
    <h4>Test conditions</h4>
    @Html.Partial("~/a.cshtml")
</div>
<div data-bind="with: testConditions()[1]">
    <h4>Second test conditions</h4>
    @Html.Partial("~/a.cshtml")
</div>

in my js file I have:

this.testConditions = ko.observableArray([
        { condition: "Yes" },
        { condition: "Yes" }
    ]);

so the question is how I can differentiate the radio buttons as with the above code all the radio buttons in my form have the same name and basically selecting one of them at the div including testConditions()[0] affects the other ones in the div including testConditions()[1] and vice versa.

I was thinking to add a second properties in the array like:

this.testConditions = ko.observableArray([
            { condition: "Yes", itemname: "group1" },
            { condition: "Yes", itemname: "group2" }
        ]);

and used that in html like:

 <div>
     <input type="radio" value="Yes" data-bind="checked: condition, name: itemname">&nbsp;<label class="YesNo">&nbsp;Yes&nbsp;</label>
     <input type="radio" value="No" data-bind="checked: condition, name: itemname">&nbsp;<label class="YesNo">&nbsp;No&nbsp;</label>
 </div>

however, it did not work. Any ideas?

Questioner
Steve Shahbazi
Viewed
34
Steve Shahbazi 2020-02-06 13:02

I found the answer:

<div>
 <input type="radio" value="Yes" data-bind="checked: condition, attr: { 'name': itemname}">&nbsp;<label class="YesNo">&nbsp;Yes&nbsp;</label>
 <input type="radio" value="No" data-bind="checked: condition, attr: { 'name': itemname}">&nbsp;<label class="YesNo">&nbsp;No&nbsp;</label>
</div>