I’m using knockoutJS to handle an editable list of website name and URL pairs in a table – there’s a button underneath to add a new item. My code is based on the lists and collections tutorial.
....
<tbody data-bind="foreach: website">
<tr>
<td><input data-bind="value: name, hasfocus: true" /></td>
<td><input data-bind="value: url" /></td>
<td><a href="#" data-bind="click: $root.removeWebsite">Remove</a></td>
</tr>
</tbody>
</table>
<button data-bind="click: addWebsite" class="btn">Add another</button>
Note I use hasfocus: true so that each time a new blank field is added they don’t have to click it with the mouse. You’ll also see in the code below (from the viewmodel function) that I’m checking the contents of the last text box in the list before I allow people to add another one.
// Add and remove
self.addWebsite = function() {
var length = self.website().length;
if (self.website()[length - 1].name == '') {
// Last site in list has no name, don't allow them to add another
return false;
}
self.website.push(new dashboardApp.website());
}
Is there a way of changing the binding during runtime – so I can give the last item focus as a prompt to the user that they should be filling it in rather than creating further blank rows, e.g. something like:
self.website()[length - 1].name.hasfocus = true;
You can accomplish this by using an observable to bind against
hasfocusrather than justhasfocus: true.One way that I like to do something like this is to add a
focusedsub-observable off of the field’s main observable. Something like:Then, bind like
data-bind="value: name, hasfocus: name.focused"and set the focused observable in your check for the last name being empty likename.focused(true).Here is a sample: http://jsfiddle.net/rniemeyer/NkYR5/
If your
nameandurlaren’t observables, then you could just add another observable specifically for controlling focus.