views:

1401

answers:

2

I'm trying to simulate an actual tab key press in JavaScript. I don't want to focus on the next element or anything like that, I just want to make it seem like the tab key has been pressed.

The reason why is because I am building a form JavaScript class where I want to be able to use the enter key just like tab. If someone is using a native BROWSER autocomplete, I need to fire the tab key to capture the selected autocomplete response. If I just move to the next input it won't capture their autocomplete selection and leave the field blank.

Any thoughts?

+1  A: 

I don't think it's possible; an article about DOM events here:

http://www.howtocreate.co.uk/tutorials/javascript/domevents

...mentions that firing an event doesn't trigger the default result of the user action, for security reasons; the script should not be able to simulate user interaction directly. You will have to simulate the behavior the keypress causes (such as focus on a field), instead of trying to actually simulate a keypress. You probably won't be able to interact with the browser's native autocomplete functionality, unless the browser explicitly provides a means for you to do so.

RMorrisey
+1  A: 

May be this kind of code may help you

<textarea  id='test'></textarea>
<script type="text/javascript">
 document.getElementById('test').onkeydown = function(e){
  if (e.keyCode == 9) {
   this.value = this.value + ' Tab Pressed!'; 
   this.focus();
   return false;
  }
 }
</script>
RayZ