How to allow up and down arrows to navigate your form fields

originally posted at http://www.goodfeelingplace.com/how-to-allow-up-and-down-arrows-to-navigate-your-form-fields
I learned something pretty cool last week. I fielded a request from a client who wanted to be able to use the up and down arrows on his keyboard to navigate a rather large form on the site I created for him. I believed it was possible but I had never done it. So after doing some research I figured out how to do it. Below is a simplistic version (put your cursor in one of the text boxes below and push the up or down arrow keys to move between them):

1-1 1-2 1-3
2-1 2-2 2-3
3-1 3-2 3-3

The HTML for the simple table is as follows:

<table border="1">
<tr>
<td>1-1</td>
<td><input id="ItemCost11" onkeydown="return checkKey(event,3,3,'ItemCost',1,1)" maxlength="30" name="ItemCost11" size="3" /></td>
<td>1-2</td>
<td><input id="ItemCost12" onkeydown="return checkKey(event,3,3,'ItemCost',1,2)" maxlength="30" name="ItemCost12" size="3" /></td>
<td>1-3</td>
<td><input id="ItemCost13" onkeydown="return checkKey(event,3,3,'ItemCost',1,3)" maxlength="30" name="ItemCost13" size="3" /></td>
</tr>
<tr>
<td>2-1</td>
<td><input id="ItemCost21" onkeydown="return checkKey(event,3,3,'ItemCost',2,1)" maxlength="30" name="ItemCost21" size="3" /></td>
<td>2-2</td>
<td><input id="ItemCost22" onkeydown="return checkKey(event,3,3,'ItemCost',2,2)" maxlength="30" name="ItemCost22" size="3" /></td>
<td>2-3</td>
<td><input id="ItemCost23" onkeydown="return checkKey(event,3,3,'ItemCost',2,3)" maxlength="30" name="ItemCost23" size="3" /></td>
</tr>
<tr>
<td>3-1</td>
<td><input id="ItemCost31" onkeydown="return checkKey(event,3,3,'ItemCost',3,1)" maxlength="30" name="ItemCost31" size="3" /></td>
<td>3-2</td>
<td><input id="ItemCost32" onkeydown="return checkKey(event,3,3,'ItemCost',3,2)" maxlength="30" name="ItemCost32" size="3" /></td>
<td>3-3</td>
<td><input id="ItemCost33" onkeydown="return checkKey(event,3,3,'ItemCost',3,3)" maxlength="30" name="ItemCost33" size="3" /></td>
</tr>
</table>

The javascript function used is as follows:

<script type="text/javascript"><!--
function checkKey(event, numRecs, numCols, myName, myRow, myCol) {
  var key = event.keyCode;
  var bSetFocus = false;
  var myId = '';
// if the left arrow has been pressed and we're not in the first column
  if( key == 37) {
  if (myCol-1 > 0) {
  myId = myName + myRow + (myCol-1);
  bSetFocus = true;
  }
  }
  // if the up arrow has been pressed and we're not in the first row
  if( key == 38) {
  if (myRow-1 > 0) {
  myId = myName + (myRow-1) + myCol;
  bSetFocus = true;
  }
  }
  // if the right arrow has been pressed and we're not in the last column
  if( key == 39) {
  if (myCol+1 <= numRecs) {
  myId = myName + myRow + (myCol+1);
  bSetFocus = true;
  }
  }
  // if the down arrow has been pressed and we're not in the last row
  else if( key == 40 ) {
  if (myRow+1 <= numCols) {
  myId = myName + (myRow+1) + myCol;
  bSetFocus = true;
  }
  }
  if (bSetFocus) document.getElementById(myId).focus();
} // end checkKey function
// --></script>

In my code I generate the HTML using PHP so when I pass the number of records to the checkKey function (3 in this example) it is the number of rows returned from a database query, and the current row for any given row of the table is the counter in a loop I use to print the table.

By the way, if you want to allow for the left and right arrows to move left and right in a form, you can do that by expanding the checkKey function to look for key code 37 (left arrow) and key code 39 (right arrow), and you’ll need to implement a column ordering scheme (like the counter I used for the rows) so you’ll know where to take the cursor.

Four Direction Code

(submitted by Mr Arrows below, but the comment fields do not accept code so I put it in the main post. I actually had trouble putting two working code samples in the same post so I just updated the main example above to include the left and right arrows)

What if there are values in each field?

These two javascript functions need to be defined, which will tell you the index of the start of the current selection and the end of the current selection (which will be the same if nothing is selected and you just have a blinking cursor in the input box). They both take as input the same object (called o below) that is passed into checkKey as the last param (called myObj there):

function getSelectionStart(o) {
  if (o.createTextRange) {
  var r = document.selection.createRange().duplicate();
  r.moveEnd('character', o.value.length);
  if (r.text == '') return o.value.length;
  return o.value.lastIndexOf(r.text);
  } else return o.selectionStart;
}
function getSelectionEnd(o) {
  if (o.createTextRange) {
  var r = document.selection.createRange().duplicate();
  r.moveStart('character', -o.value.length);
  return r.text.length;
  } else return o.selectionEnd;
}

Then you need to define some variables inside the checkKey function, to get the current input value and the index of the cursor position within that value:

  var inputVal = myObj.value,
  startIndex = getSelectionStart(myObj);
  endIndex = getSelectionEnd(myObj);

I only use startIndex because it will be the same as endIndex when nothing is highlighted or selected in the input box.

Next you can use a simple regular expression (or any other string function you want) to see if there is any text before (for the left arrow condition) or after (for the right arrow condition) the cursor. For example, this is the code I use when when the left arrow has been pressed:

  var testBC = inputVal.substring(0, startIndex);
  var blankRE=/^\s*$/;
  //alert("beforeCursor is '"+testBC+"');
  // if the regular expression test passes, then there is nothing to the left and we can move cells
  if (blankRE.test(testBC)) {
  var nextField = document.getElementById(columns[colIndex-1]+String(myRow));
  nextField.focus();
  //If we are moving into a select dropdown, restore the previously selected value half a second after it switches to the first or last option (I don't know how to prevent that, so this is my workaround):
  if (nextField.tagName=="SELECT") {
  var cur_ind = nextField.options.selectedIndex;
  var cur_val = nextField.options[nextField.options.selectedIndex].value;
  var cur_text = nextField.options[nextField.options.selectedIndex].text;
  setTimeout(function(){nextField.options.selectedIndex=cur_ind}, 5);
  }
  return false;
  }

Join the Conversation

4 Comments

  1. hi…need a little help here not good in programming in php. how can i do that navigation though arrow keys in navigating table rows of record from database, meaning my onkeyup is on the tr.

    thanks…

  2. Hello there,
    I just checked and it seems like having the onkeyup on the tr element is fine since it is an “intrinsic event” (as noted at http://www.w3.org/TR/REC-html40/interact/scripts.html). So in order to make it work, each tr element needs to have a unique id. In my example, the input elements have unique ids. So when you print the records from your database, initialize a counter (like $rowCount or $index or something) to equal zero, then when you print out each row increment the counter and put the counter in the id of the tr element. Or you could just use the key of the database row like this (assuming the records are in an array called $databaseRows):

    $numRecs = count($databaseRows);
    foreach ($databaseRows as $dbKey=>$dbRow) {
      echo “<tr id = ‘”.$dbKey.”‘
        onkeyup=\”return checkKey(event,'”.$numRecs.”‘,'”.$dbKey.”‘)”
        ><td>”.$dbRow[“myDataColumnLabel”].”</td></tr>”;
    }

    The code above would need to be expanded to include all your data fields, but that’s the idea. You would also need to modify the checkKey javascript function to ignore the 3rd element (the fieldname), since you will be shifting focus on the rows, not the individual table data (td) elements.

    I’m actually not sure where the cursor would go in this case though, since you are setting the focus on a table row and not an individual data element. If it doesn’t put the cursor where you want it I recommend specifying a specific td, like in my example above.
    Regards,
    Robert

  3. This is the js code for all arrows. I needed it so I post it here.

    [code doesn’t show up well in comments so I included it in the main post -Robert]

Leave a comment

Your email address will not be published. Required fields are marked *

CommentLuv badge