Reputation: 29693
I have simple table (using knockout.js
), with feature to select row
http://jsfiddle.net/aDahT/447/
Now I want add next feature. Select row by keypress of first letter of the record's name.
e.g. if user press b
then record bbb
is selected.
if user press h
then record Ham
is selected.
How can I implement it?
Upvotes: 0
Views: 2596
Reputation: 13278
Here is a solution: http://jsfiddle.net/VEnsz/4/
I have data bound to the outer element:
<div style="width: 30em; max-height: 6em; overflow-x: hidden; overflow-y: auto; border: 1px groove grey" data-bind="event: {keypress: selectByKeyPress }">
(You may pick another element in your application to attach the key press event to).
...and added the following function to your model:
self.selectByKeyPress = function(data, e)
{
var key = String.fromCharCode(e.keyCode).toLowerCase();
var items = self.allItems();
for (var j=0; j<items.length; j++) {
if (items[j].toLowerCase().indexOf(key) == 0) {
self.selectCurrent(items[j]);
return;
}
}
}
Although you may need to refine this solution somewhat, I feel it is more in keeping with the 'knockout' way of doing things, so hopefully should provide you with a good basis to build your functionality on.
Upvotes: 1
Reputation: 198
First of all, if you are forking a fiddle, run JSLint first. It will help you to make cleaner and more correct code. I came out with this: http://jsfiddle.net/a0viedo/Guf3u/.
Using event.timeStamp
inside keyPress()
handler you could determine if the user is typing or if its starting to type a new word.
Notice the (not so)little details:
Hope it gives you any good idea.
Upvotes: 1