2

I need to be able to replace a keystroke with jQuery. When the right arrow is pressed, I want the tab key to be pressed instead. So far I have:

<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="jquery.simulate.js"></script>
<script type="text/javascript">
    $(function () {
        $("select").each( function() {
                $(this).keydown(function(event) {
                    if (event.which == '39') {
                        $(this).simulate("keydown", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        $(this).simulate("keypress", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        $(this).simulate("keyup", { keyCode: 9, ctrlKey: false, shirtKey: false });
                        return false;
                    }
            });
        });
    });
</script>

39 is the right arrow, and 9 is the tab button. Also, the simulate keydown recursively calls the event handler, which is obviously bad, but even without that line, this still doesn't work.

I'm using jquery.simulate.js located at (http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/simulate/jquery.simulate.js?r=6063) because I couldn't find a way to simulate a keypress with just jQuery.

The keypress just doesn't simulate the actual key press.

Brandon
  • 779
  • 5
  • 9
  • 28
  • 2
    wouldn't be easier to `focus` on the correct element (if you are using this to do a `tab`) – balexandre May 19 '11 at 20:50
  • 1
    Do you actually need to simulate a tab or just move focus, if you are just trying to move focus to the next element it may be easier to do $('#nextElement').focus(); – ihumanable May 19 '11 at 20:53
  • focusing on the next element would be okay, but i'm trying to do this on a automatically generate page, so i have no way of knowing the next element id, name, or anything like that. i just know i want to shift focus to the next tabindex. – Brandon May 19 '11 at 20:59

1 Answers1

2

You can't simulate actual keypresses with javascript. It's a core component of browser security. Imagine being able to simulate Alt-Tab, or Ctrl-Shift-Del.

You can, of course, define a method that encapsulates the behavior you want to trigger, and call that method when specific keys are pressed.

So, for example, to jump to the next select element when someone presses the right arrow while on another select element, I'd keep a list of all the select elements on the page; when the right-arrow is pressed, I'd find the position of the currently-focused select in that list, and .focus() the next one.

quasistoic
  • 4,657
  • 1
  • 17
  • 10