繁体   English   中英

使用 javascript 在 Enter 键上提交表单

[英]Submit form on Enter key with javascript

我不确定我在这里做错了什么。 我希望输入键和单击按钮一样工作。

<form action="" method="get" class="priceOptionForm" name="priceOptionForm">
<input name="paypal_email" type="text" value="whatever" id="email"></label>
<a href="javascript:void(0);" class="bluebtn" id="profile_price" style="width:60px;margin-top:5px;">Save all</a>
</form>

尝试这个:

document.getElementById('email').onkeydown = function(e){
   if(e.keyCode == 13){
     // submit
   }
};

请使用下面的代码片段...它应该添加到脚本块中

<script>
    document.onkeydown=function(evt){
        var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
        if(keyCode == 13)
        {
            //your function call here
        }
    }
</script>

以下所有代码都应添加到脚本块或文件中。 定义提交函数:

function submitForm(){
    document.priceOptionForm.submit();
    document.priceOptionForm.method='post';
}

对于提交表单的输入键:

document.onkeydown=function(){
    if(window.event.keyCode=='13'){
        submitForm();
    }
}

为了链接工作:

document.getElementById("profile_price").onclick=submitForm;

您可以参考http://jsfiddle.net/honglonglong/YMX2q/进行一些尝试。

使用<input type="submit">而不是链接。 然后回车键将自动工作。

简单地制作一个像这样的隐藏按钮
HTML

<input type="submit" id="submitbtn"  />

CSS

#submitbtn{display:none;}

当用户点击回车按钮时,表单将被提交
不要忘记输入 type="submit"

// Process form if use enter key. put script in head.    
document.onkeyup = enter;    
function enter(e) {if (e.which == 13) submitForm();}

// uses keyup not down as better practice imo    
// submitForm() is user function that posts the form

您可以在表单标签中放置默认按钮 ID 会自动触发

<form id="form1" runat="server" defaultbutton="Button1">

<asp:Button ID="Button1" runat="server" Text="Button"

    OnClick = "Button1_Click" />

<asp:Button ID="Button2" runat="server" Text="Button"

    OnClick = "Button2_Click" />

<asp:Button ID="Button3" runat="server" Text="Button"

    OnClick = "Button3_Click" />

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

</form>

当用户单击提交按钮( 或 )或在编辑表单中的字段(例如 )时按下 Enter时,将触发提交事件。 直接调用 form.submit() 方法时,事件不会发送到表单。 检查文件

哦,那是因为 HTML 表单元素无法将链接识别为按钮,要单击……您需要将其替换为按钮……

<input type="submit" value="this will display on your button" onClick="javascript:void(0)">

但如果你想让它看起来像一个链接,你应该在 css 中做到这一点

<style type="text/css">
input{background-color:white;border:0 none;}
</style>

暂无
暂无

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

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