JavaScript "Excel-like" Form Editing
A few days ago I was asked to generate a solution to enable the end-user to edit his or her web form in an excel-like mode. This means that he or she wouldn't have to click on a field in order to get focus to it, they will be doing so using the arrow keys instead.
And when in Web World, client side scripting means JavaScript! Yay!
The idea I had is to create a kind of a matrix and then figuring out which fields were on the sides in quite a simple calculation.
Once I had that in mind, the implementation went on quite easy... I decided to name each field using a single format: MyField_<row number>_<column number>. Then, when I have the field name, I'll be able to easily figure out who's next to it, using a simple calculation method.
Now to the code -
The HTML
As I said, all I did here was naming the fields in the format I had decided on and registering to the field's onkeydown event:
<form>
<input type="text" id="field_1_1" onkeydown="move(this)" />
<input type="text" id="field_1_2" onkeydown="move(this)" />
<input type="text" id="field_1_3" onkeydown="move(this)" />
<br /><br />
<input type="text" id="field_2_1" onkeydown="move(this)"/>
<input type="text" id="field_2_2" onkeydown="move(this)" />
<input type="text" id="field_2_3" onkeydown="move(this)" />
<br /><br />
<input type="text" id="field_3_1" onkeydown="move(this)"/>
<input type="text" id="field_3_2" onkeydown="move(this)" />
<input type="text" id="field_3_3" onkeydown="move(this)" />
</form>
|
The JavaScript
This wasn't tricky too. What I did here was to parse the field name, to get its row and column and then to calculate the next field to focus on, according to the arrow that was clicked:
var fieldConstName = "field_[ROW]_[COL]";
function move(object)
{
var row = object.id.substring(object.id.indexOf("_") + 1, object.id.lastIndexOf("_"));
var col = object.id.substring(object.id.lastIndexOf("_") + 1);
var nextField;
switch (event.keyCode)
{
case 40: /* Down arrow */
row++;
break;
case 38: /* Up arrow */
row--;
break;
case 39: /* Right arrow */
col++;
break;
case 37: /* Left arrow */
col--;
break;
default: /* This is not an arrow! */
return;
}
var newFieldName = fieldConstName.replace("[ROW]", row).replace("[COL]", col);
var nextField = document.getElementById(newFieldName);
if (nextField != null)
{
nextField.focus();
}
}
|
It is necessary to mention that this is only a POC and it has been tested only on my machine, with IE 7 and Windows Vista... I believe this will not work smoothly on Mozilla...
All the best,
Shay.