Binding dynamically created table entries with KnockoutJS
My questions stem from having a dynamically generated table. How can I
bind the enabled status of a checkbox in each row of said table to an
expression that is evaluating whether or not there are a given number of
checked boxes in that column?
Here's an example of my table:
<table>
<tr>
<th>Happy</th>
<th>Name</th>
<th>Status</th>
<th>Label</th>
</tr>
<tr>
<td>
<input type="checkbox" data-bind="checked: HappyPeople, enabled :
HappyPeople.length < 5" />
</td>
<td>
<input type="text" />
</td>
<td>
<p></p>
</td>
</tr>
<tr>
<td>
<input type="checkbox" data-bind="checked: HappyPeople, enabled :
HappyPeople.length < 5" />
</td>
<td>
<input type="text" />
</td>
<td>
<p></p>
</td>
</tr>
<tr>
<td>
<input type="checkbox" data-bind="checked: HappyPeople, enabled :
HappyPeople.length < 5" />
</td>
<td>
<input type="text" />
</td>
<td>
<p></p>
</td>
</tr>
var viewModel = {
HappyPeople : ko.observableArray()
};
Or, here's a jsfiddle of the (non-working) example of what I'm trying to do
Looking at that fiddle / code, how can I limit the number of happy people
to say 5, and if 5 happy people are checked, the rest of the checkboxes
are disabled. My thinking was, bind the checked of each checkbox to an
array, then also bind that checkbox's enabled property to the length of
said array.
Keeping in mind that my table entries will all be laid out dynamically, I
think I may need to use a template --- that sounds like the right thing to
use, but I'm unsure. I don't fully understand templates. I'm already using
ASP.NET MVC4 to do a lof of the heavy lifting, looping through some data &
rendering out a for each necessary entry, so a template may be the wrong
thing to use.
I've got some of this working with javascript/jquery, but it's maddening
handling all of the states by hand. Knockout would make this a lot easier.
No comments:
Post a Comment