Posted By

kouphax on 02/27/09


Tagged

javascript jquery


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

LeeRJohnson
kikuchiyosesa
millano5
a1ias


jQuery Tab On Return Key Press


 / Published in: JavaScript
 

Simple function for turning RETURN key presses into TAB key presses. Focuses input element next in the DOM (usually makes sense), unless we are at the end of the form, at which point it focuses the first element in the form for cyclical purposes.

  1. $('input').live("keypress", function(e) {
  2. /* ENTER PRESSED*/
  3. if (e.keyCode == 13) {
  4. /* FOCUS ELEMENT */
  5. var inputs = $(this).parents("form").eq(0).find(":input");
  6. var idx = inputs.index(this);
  7.  
  8. if (idx == inputs.length - 1) {
  9. inputs[0].select()
  10. } else {
  11. inputs[idx + 1].focus(); // handles submit buttons
  12. inputs[idx + 1].select();
  13. }
  14. return false;
  15. }
  16. });

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: kcmr on March 12, 2009

$('input').keypress(function(e){ /* ENTER PRESSED/ if(e.keyCode == 13){ / ONE LINER TO FOCUS ELEMENT/ try{ ($(this).blur(); }catch(e){ / IGNORE */ } } });

Posted By: kouphax on March 12, 2009

@kcmr - 'fraid not - $(this).blur() doesn't set focus on the next element merely blurs the current element.

You need to login to post a comment.