tags:

views:

24

answers:

1

Hi All,

 I am using jquery in one of my projects. I have a scenario where I have to add keyboard events to the td cells of a table to move up and down in them. I was able to achieve this using the following code.

Here is my code:

<script type="text/javascript">
 var tds = jQuery("#myTable td");
 tds.bind('keyup', function(event){        
      var key = event.which;
      moveSelection(key, jQuery(this), tds);
      event.preventDefault();                        
 });
 function moveSelection(key, current_td, all_tds){    
    var index = parseInt(current_td.attr("id"));        
    if (key == 13) {
        current_td.click();
      } else if(key == 38) {              
        if(all_tds[index - 1]){
            all_tds[index - 1].focus();
        }
      } else if(key == 40) {
          if(index < all_tds.length){
            var next_index = index + 1;
            if(next_index < all_tds.length){
                all_tds[index + 1].focus();
            }                
         }
    }            
}    

13=Enter, 38=PageUp, 40=PageDown.

I was able to move through the td cells if the page has no scroll bars. But when the page has scroll bars, when I use PageUp/PageDown keys two things happen.

  1. My page scrolls up/down based on the key pressed.()
  2. The respective td selection moves/up based on the key pressed.

In the first case, it might be because of the events are bound to the page as well as my table tds. How can I prevent this. I dont want my page to scroll when I am dealing with my table. I tried a lot but failed. Looking here for some help.

Any help greatly appreciated.. Thanks in advance...

A: 

try to add an "return false" at each key handle. or this one:

if(event.stopPropagation) {
 event.stopPropagation(); // standard browsers
} else {
 event.cancelBubble = true; // IE
}
chriszero
that didn't solve the problem. It behaves the same as before.