Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ID in KnockoutJS code block

I've done some research on the subject, but I couldn't find anything really useful for this.

My problem:

I have a list of Items(in SharePoint) and I am using KnockoutJS foreach statement to display a table with all of them. Like this:

Quantity | Price | Total_Price | RadioButton1 | RadioButton2

As you can see there are 2 radio buttons and it is mandatory to use an id attribute for them ( because I am also using JqueryUI - label for='id of element' - )

I tried something like this >

Example of code:

.....

<% int i=1; %>
< ! - - ko foreach: Items --> ........

     <input type="radio" id="Yes+<%=i %>"/>
     <label for="Yes+<%=i %>" >Yes</label>
     <input type="radio" id="No+<%=i %>" />
     <label for="No+<%=i %>">No</label>

     </td>

<%i++; %>

< !-- /ko -->

The thing is asp code does not recognize ko foreach iterations.

Any ideas ? Thank you

like image 721
Cosmin Grigore Avatar asked Oct 12 '12 13:10

Cosmin Grigore


1 Answers

Can you put an Id on the Item viewmodel then use that?

< ! - - ko foreach: Items --> ........

 <input type="radio" data-bind="attr: { id: 'Yes' + Id }" />
 <label data-bind="attr: { 'for': 'Yes' + Id }" >Yes</label>
 <input type="radio" data-bind="attr: { id: 'No' + Id } />
 <label data-bind="attr: { 'for': 'No' + Id }">No</label>

 </td>
< !-- /ko -->

or use the index observable as Macropus suggested:

< ! - - ko foreach: Items --> ........

 <input type="radio" data-bind="attr: { id: 'Yes' + $index() }" />
 <label data-bind="attr: { 'for': 'Yes' + $index() }" >Yes</label>
 <input type="radio" data-bind="attr: { id: 'No' + $index() } />
 <label data-bind="attr: { 'for': 'No' + $index() }">No</label>

 </td>
< !-- /ko -->
like image 99
Mike Simmons Avatar answered Oct 18 '22 16:10

Mike Simmons