Code
// Enable user to move focus in a grid of inputs with Ctrl + Up, Down, Left, Right, Home, End
// Cocould be called again after more rows are created.
// Deerchao@gmail.com
// Usage:
// -------------- Html ----------------
// <Tr class = "dataRow">
// <Td> <input/> </td>
// <Td> <input/> </td>
// <Td> <input/> </td>
// </Tr>
// <Tr class = "dataRow">
// <Td> <input/> </td>
// <Td> <input/> </td>
// <Td> <input/> </td>
// </Tr>
// -------------- Script -------------
// JQuery. excel ('datarow ');
JQuery. extend ({
Excel: function (rowClass ){
Var keys = {left: 37, up: 38, right: 39, down: 40, home: 36, end: 35 };
RowClass = rowClass? RowClass: '. excel ';
If (rowClass [0]! = '.')
RowClass = '.' + rowClass;
$ (RowClass). unbind ('keyup', onkeyup). bind ('keyup', onkeyup );
Function onkeyup (evt ){
Var ctrlOnly = evt. ctrlKey &&! Evt. altKey &&! Evt. shiftKey;
Switch (evt. keyCode ){
Case keys. down:
Go ("down ");
Break;
Case keys. up:
Go ("up ");
Break;
Case keys. left:
If (ctrlOnly)
Go ("left ");
Break;
Case keys. right:
If (ctrlOnly)
Go ("right ");
Break;
Case keys. home:
If (ctrlOnly)
Go ("home ");
Break;
Case keys. end:
If (ctrlOnly)
Go ("end ");
Break;
}
Function go (){
Var td = require (evt.tar get). closest ('td ');
Var tr = $ (evt. currentTarget );
Var toFocus = null;
Switch (){
Case 'Home ':
ToFocus = lastInput (td. prevAll ('td '));
Break;
Case 'end ':
ToFocus = lastInput (td. nextAll ('td '));
Break;
Case 'left ':
ToFocus = firstInput (td. prevAll ('td '));
If (! ToFocus)
ToFocus = lastInput (tr. prev ('tr '+ rowClass). children ('td '));
Break;
Case 'right ':
ToFocus = firstInput (td. nextAll ('td '));
If (! ToFocus)
ToFocus = firstInput (tr. next ('tr' + rowClass). children ('td '));
Break;
Case 'up ':
ToFocus = firstInput (tr. prev ('tr '+ rowClass). children ('td'), td. prevAll ('td '). size ());
Break;
Case 'lowdown ':
ToFocus = firstInput (tr. next ('tr' + rowClass). children ('td '), td. prevAll ('td'). size ());
Break;
}
If (toFocus ){
ToFocus. focus ();
}
}
Function firstInput (tds, start ){
If (! Start)
Start = 0;
For (var I = start; I <tds. size (); I ++ ){
Var inputs = $ (tds [I]). children ('input, select, textarea ');
If (inputs. size ())
Return inputs [0];
}
Return null;
}
Function lastInput (tds ){
For (var I = tds. size ()-1; I> = 0; I --){
Var inputs = $ (tds [I]). children ('input, select, textarea ');
If (inputs. size ())
Return inputs [0];
}
Return null;
}
}
}
});