I have a web page with 16 textboxes arranged in a 4×4 grid. The idea is that a user will type precisely one character into each textbox (specifically, a letter). You can see this page online at http://fuzzylogicinc.net/Boggle/EnterBoardClientSide.aspx
What I want to happen is the following:
- When the page loads the upper left textbox is focused
- Typing a letter in the textbox should enter that letter and then automatically set focus to the next textbox in the grid
- If the user selects a textbox (either via the mouse or by Shift-Tabbing back to a previous textbox) the entry in the textbox should be selected so that they can just type the new letter to overwrite the old one.
I’ve got this working for the most part, but have one vexing problem – namely, if a user types the letters too fast, some textboxes are left empty, as if the code that whisks the user to the next textbox occurs before the browser has a chance to actually commit the letter to the textbox that had focus (if that makes any sense). If you visit my live demo and start typing at a decent rate, you’ll see that some textboxes are left blank.
My JavaScript, which can be seen it its entirety here, has the following code for selecting/focusing/moving to the next textbox:
$("input.BoggleGridCell")
.focus(function () {
$(this).select();
})
.keyup(function (event) {
var code = (event.keyCode ? event.keyCode : event.which);
if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
var currentId = $(this).attr('id');
var leftDigit = currentId.substring(1, 2);
var rightDigit = currentId.substring(2, 3);
if (leftDigit != 3 || rightDigit != 3) {
if (rightDigit == 3) {
rightDigit = 0;
leftDigit++;
}
else {
rightDigit++;
}
var moveToId = 'c' + leftDigit + rightDigit;
var newCell = document.getElementById(moveToId);
if (newCell)
newCell.focus();
}
else {
$("#solve").focus();
}
}
});
Note that all my textboxes in the grid have a CSS class of BoggleGridCell. Each textbox in the grid has an id of the form cXY, where X is the row number and Y is the column number. I have a bit of code in the keyup event handler that examines this X and Y value of the current textbox’s id to determine the next textbox to focus.
What’s going on here? My intuition is that when typing at a sufficient pace that the keyup event for the first key press hasn’t completed by the time the keyup event for the subsequent key press is raised.
Thanks!
Figured a workaround… I ended up using jQuery’s
keypressevent plus JavaScript’ssetTimeoutfunction. Here’s the final code that appears to work as expected in IE 8, FF 3, and Google Chrome.