Return Key: How to Focus the Right Shape

I have more than one form on one page: I would like to know if there is a way to submit the correct form when the user presses the "return key key" key?

thank

+3
source share
3 answers

How about this:

<form id="form1">
    <input type="text" />
</form>
<form id="form2">
    <input type="text" />
</form>

<script type="text/javascript">
    for (var i = 0; i < document.forms.length; i++) {
        document.forms[i].onkeypress = function(e) {
            e = e || window.event;
            if (e.keyCode == 13)
                this.submit();
        }
    }
</script>

Basically, in each form, fire an onkeypress event for each of them, which checks the input (keycode == 13) and triggers the submission in this form.

+1
source

I assume that in the right form you mean the form the user is working on!

, , , , .

, ( , , )

+1

Check which element has focus. Check which form is its parent. Submit.

document.onkeypress = function() {

    var element = activeElement.parentNode;

    while(element.nodeType != /form/i) {
        element = element.parentNode;
    }

    element.submit();
}
0
source

Source: https://habr.com/ru/post/1772149/


All Articles