简体   繁体   English

Javascript / html用返回键提交表单?

[英]Javascript/html Submit form with return key?

I have a form which performs a javascript when submit is clicked. 我有一个单击提交时执行javascript的表单。 I can't seem to figure out how to do the same thing when the return key (13) is used. 使用返回键(13)时,我似乎无法弄清楚该怎么做。

HTML: (note MakeRequest() is a JS method which performs a request on another php page and returns results to JSresult.) HTML :(请注意,MakeRequest()是一个JS方法,该方法在另一个php页面上执行请求,并将结果返回给JSresult。)

<form name="SearchForm">
Name: <input type = "text" name = "Name" id="Search"
placeholder="Search stuff here...">
<button type="button" id "Request" onClick="MakeRequest()"">Search</button>

</form>
div id="JSresult">
</div>

Replace your button with a submit input and move the function to form onSubmit, instead of button onClick : 将按钮替换为提交输入,然后将函数移至表单onSubmit,而不是按钮onClick:

<form name="SearchForm" onSubmit="MakeRequest();">
    Name: <input type = "text" name = "Name" id="Search" placeholder="Search stuff here..." />
    <input type="submit" id="Request" value="Search" />
</form>

Here is an unobtrusive approach that should do the trick: 这是一种应该做到这一点的简便方法:

<script>
    window.onload = function(){
        document.getElementById("Search").onkeydown = function(e){
            key = (e.keyCode) ? e.keyCode : e.which;
            if(key == 13) {
                document.getElementById("Request").click();
            }
        };
    };
</script>

Just copy that into the head of your HTML file. 只需将其复制到HTML文件的head

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

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