1

I have the following Javascript that if I should press the down arrow and the cursor will go down to the next row. I can't seem to make that happen. Any suggestions?

jQuery

$('td').keypress(function(evt){
    if(evt.which == 40){
        event.preventDefault();
        var cellindex = $(this).index()
        var rowindex = $(this).parents('tr').index() + 1
        $(this).parents('table').find('tr:eq('+rowindex+') td:eq('+cellindex+')').focus()
    }
})

HTML

<table>
  <tr><td contenteditable>My_Name</td><td>Surname</td></tr>
  <tr><td contenteditable>My_Name2</td><td>Surname2</td></tr>
</table>
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
varcor
  • 63
  • 1
  • 2
  • 10

1 Answers1

0

Use this:

jQuery(document).ready(function(){

    $('td').keydown(function(evt) {
        if(evt.keyCode == 40) {
            event.preventDefault();
            var cellindex = $(this).index()
            var rowindex = $(this).parents('tr').index() + 1
            $(this).parents('table').find('tr:eq('+rowindex+') td:eq('+cellindex+')').focus()
        }
    });
});

or can use for down and up key event in this code

jQuery(document).ready(function(){
$('td').keydown(function(evt){
    if(evt.keyCode == 40){
        event.preventDefault();
        var cellindex = $(this).index()
        var rowindex = $(this).parents('tr').index() + 1
        $(this).parents('table').find('tr:eq('+rowindex+') td:eq('+cellindex+')').focus()
    }else if (evt.keyCode == 38){
            event.preventDefault();
        var cellindex = $(this).index()
        var rowindex = $(this).parents('tr').index() - 1
        $(this).parents('table').find('tr:eq('+rowindex+') td:eq('+cellindex+')').focus()
    }
})
});

jsfiddle

Harutyun Abgaryan
  • 2,013
  • 1
  • 12
  • 15
  • A little explanation of your solution would be helpful. – showdev Oct 08 '14 at 19:47
  • use on keydown for key event and event.keyCode =40 this code for down arrow, you need get on keyDown and creat if keydown code ==40 then next td – Harutyun Abgaryan Oct 08 '14 at 19:50
  • 1
    `modifier and non-printing keys ... trigger keydown events but not keypress events` -- [api.jquery.com](http://api.jquery.com/keypress/) – showdev Oct 08 '14 at 19:52
  • That Worked for Regular HTML file for me. I use smarty/php combo and it didn't seem to work. i put the same script in a .tpl and it didn't work. i know the Jquery is being accessed because another function works. – varcor Oct 08 '14 at 20:30
  • It did not. I'm wondering if smarty template for some reason is not seeing the code – varcor Oct 08 '14 at 20:45
  • sorry but your question fir jquery keypress and not fir smarty thmeplate – Harutyun Abgaryan Oct 08 '14 at 20:47