admin管理员组

文章数量:1310502

Is it possible to use the enter key to move to the next input field in a form? I also want to use the tab, but the enter key would be nice too.

FYI - I do have several textareas and I need to use the enter key for returns when they type. Will this be a conflict?

Thank you. Erik

Is it possible to use the enter key to move to the next input field in a form? I also want to use the tab, but the enter key would be nice too.

FYI - I do have several textareas and I need to use the enter key for returns when they type. Will this be a conflict?

Thank you. Erik

Share Improve this question asked Apr 12, 2012 at 21:46 ErikErik 5,79127 gold badges72 silver badges120 bronze badges 4
  • 1 That would be really unintuitive, since for textareas, a newline can be entered as well – Ayush Commented Apr 12, 2012 at 21:47
  • 3 Can you? Yes. Should you? No. Messing with default browser behavior is bad form. The browser trains a user that this does this and that does that - at least for me, if you stray from that, that web page irritates me. – Snuffleupagus Commented Apr 12, 2012 at 21:49
  • +1 for a genial idea. Yes, it's not intuitive, but I caught my self hitting enter on an not fulfilled form. Now, rethinking about your question, having seen my focus on a forgotten input is TOTALLY A GREAT IDEA. (not to talk that hitting enter after all (if all inputs entered) it will submit the form!) +100 – Roko C. Buljan Commented Apr 12, 2012 at 22:07
  • It is possible but don't do that. The TAB Key is meant for that. – Joberror Commented Apr 13, 2012 at 14:44
Add a ment  | 

2 Answers 2

Reset to default 6

If you were to add a class called 'TabOnEnter' to the fields where you want to cycle on enter.

$(document).on("keypress", ".TabOnEnter" , function(e)
  {
    //Only do something when the user presses enter
    if( e.keyCode ==  13 )
    {
       var nextElement = $('[tabindex="' + (this.tabIndex+1)  + '"]');
       console.log( this , nextElement ); 
       if(nextElement.length )
         nextElement.focus()
       else
         $('[tabindex="1"]').focus();  
    }   
  });

//Hidden inputs should get their tabindex fixed, not in scope ;)
//$(function(){ $('input[tabindex="4"]').fadeOut();  })

Not as cute as the previous answer, but it works now :

http://jsfiddle/konijn_gmail_/WvHKA/

This way you use a standard HTML feature ( tabindex ) to determine the cycling order. Hidden elements should have their tabindex removed.

Shot in the dark (assuming your textareas are lined up):

$(".myTextareas").keypress(function(e) {
    if(e.which == 13) {
        $(this).next('.myTextareas').focus();
    }
});

本文标签: javascriptUse Enter Key to move to inputsStack Overflow