Textbox keyboard navigation using jQuery

This script will turn your tabular HTML textbox into spreadsheet-like entry, with textbox navigation using your keyboard’s arrow keys. Please note that each textbox’s ID should be “field_(xpos)_(ypos)”. Those IDs can be generated automatically using PHP.


// KEYBOARD NAVIGATION

$(document).ready(function(){

	$('input[type=text]').each(function() {
		this.onfocus = function() {
			var cur_id = this.id.split('_');
			var cur_x = parseInt(cur_id[1]);
			var cur_y = parseInt(cur_id[2]);
			
			this.onkeydown = function(event) {
                    if(!event) event = window.event;
                    funcKeyDown(event,cur_x,cur_y);
            };
		};			
	});
});

function funcKeyDown(evt, cur_x, cur_y) {

	switch(evt.keyCode) {
		case 39: 	// right key
			var next_x = parseInt(cur_x + 1);
			var next_y = cur_y;
			$('#field_' + next_x + '_' + next_y).focus();
			return false;		
		
		case 37: 	// left key
			var next_x = parseInt(cur_x - 1);
			var next_y = cur_y;
			$('#field_' + next_x + '_' + next_y).focus();
			return false;		
		
		case 38: 	// up key
			var next_x = cur_x;
			var next_y = parseInt(cur_y - 1);
			$('#field_' + next_x + '_' + next_y).focus();
			return false;		
		
		case 40: 	// down key
			var next_x = cur_x;
			var next_y = parseInt(cur_y + 1);
			$('#field_' + next_x + '_' + next_y).focus();
			return false;		
	
	}
}

Iklan