开发者

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.


<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!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜