简体   繁体   中英

HTML capture enter key and tab key

I want to prevent the enter key from submitting the form, I want it to act as a TAB key to just jump to the next field in the form or the next element.

Is this possible in HTML/JS?

if not possible to make the enter button act as a tab, is there a way to prevent the submission of the form and make only the form be submitted using the buttons on the HTML??

EDIT:

I have received a solution to this problem when I was asking for another problem!

here you can find the solution.

For accessibility/usability reasons, you really shouldn't prevent the Enter key from submitting the form (assuming the browser was going to do that anyway; IIRC, some older browsers didn't).

Assuming that you want to do this because the submit button has a click handler you'd like to happen for every form submission, you should instead move that code into a separate function and invoke it from a the form's submit event.

In jQuery, it would look something like:

$('#myForm').submit(function(e) {
        if (!isValid()) {
            e.preventDefault();  // Could also be `return false;` but I prefer preventDefault.
        }
});

See the docs .

FYI, if you're trying to do some validation, you should check out the validation plugin .

It might be possible to solve this using some jQuery - although I don't know how to imitate a keypress.

$(document).keyup(function(e) {
  if(e.keyCode == 13)
  {
    //Code to imitate keypress of Tab key
  }
});

Edit: Made a quick jsFiddle to "imitate" tab presses, which would go to the next field like you mentioned. (This one works based on the Enter key being pressed in a field)

jsFiddle

<html>
<body>
<script>
function tmpFn(val){
    if(event.keyCode=='13'){
    if (val<4)
        document.forms["yourform"].elements["box" + (val+1)].focus();
    else
        document.yourform.submit();
    return false;
    }
    return true;
}
</script>
<body>
<form name="yourform" action="#">
<input type="text" name="box1" onkeypress="return tmpFn(1)"><br>
<input type="text" name="box2" onkeypress="return tmpFn(2)"><br>
<input type="text" name="box3" onkeypress="return tmpFn(3)"><br>
<input type="text" name="box4" onkeypress="return tmpFn(4)"><br>
<input type="submit" name="done" value="Submit">
</form>
</body>
</html>

EDIT : Refrain from using 'eval'.. Thanks Tim and Andy!

Off the top of my head, to prevent the enter button from submitting the form, don't use a submit button, rather use a <input type="button" ... onclick="submitForm();"> to call javascript to submit the form. I could be wrong, but I believe this should prevent pressing enter on any other element submitting the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM