简体   繁体   English

当不是默认表单操作时,如何使用JavaScript或jQuery通过Enter键提交表单

[英]How do I use JavaScript or jQuery to submit a form by using the Enter key, when not the default form action

I have a page that has three "forms" that are apparent to the user. 我有一个页面,其中包含对用户显而易见的三个“表单”。 Under the hood, the page has only ONE form, using html:form as the JSP object controlling the entire page. 在后台,页面只有一个表单,使用html:form作为控制整个页面的JSP对象。 When a user clicks on the image that is used for the individual submit buttons, it triggers an onClick() function, which bypasses the form's action and executes another action instead. 当用户单击用于单个提交按钮的图像时,它将触发onClick()函数,该函数绕过表单的操作并执行另一个操作。

<html:form action="foo.do">
    <html:text property="name" styleClass="input" />
    <img src="bar.jpg" onClick="myFunction();" />
</html:form>

<script>
    function myFunction(){
        document.forms[0].action = "realPage.do";
        document.forms[0].submit();
    }
</script>

This script works, sending the user not to the default "foo.do" but rather to the destination of the function (realPage.do) 该脚本可以正常工作,而不是将用户发送到默认的“ foo.do”,而是发送给函数的目标地址(realPage.do)

However, the problem is my users want to be able to submit the form just by hitting 'Enter' on their keyboard when in any one of the fields, of the particular "form" they want to submit. 但是,问题是我的用户希望仅通过在想要提交的特定“表单”字段中的任何一个字段中单击键盘上的“ Enter”就可以提交表单。 How can I use JavaScript or jQuery to recognize which "form" and, hence, which input field the user is in, detect the press of the 'Enter' key and submit using the same function as the button? 如何使用JavaScript或jQuery识别用户所在的“表单”,从而识别用户所在的输入字段,并检测按下“ Enter”键并使用与按钮相同的功能提交?

This should solve your problem 这应该可以解决您的问题

$(document).ready(function(){
    $("input").keyup(function (e) {
        if (e.keyCode == 13) {
            // Submit your form here
        }
    });
});

I would probably arrest the form submit and detect which element has focus. 我可能会逮捕表单提交并检测哪个元素具有焦点。 Something like this, where each pseudo-form has an identified wrapper element: 诸如此类,每个伪表单都有一个已标识的包装器元素:

$(function() { // document.ready
    $('#myform').submit(function(event) {
        event.preventDefault();

        if ( $('#pseudoForm1 input').is(':focus') ) { ... }
        else if ( $('#pseudoForm2 input').is(':focus') ) { ... }
        else if ( $('#pseudoForm3 input').is(':focus') ) { ... }
    });
});

You could start with this - 您可以从这里开始-

$('input').keypress(function(e) {
    if(13 == e.keyCode) {
        var closestForm = $(this).closest('form');
        $(closestForm).submit();
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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