简体   繁体   English

在表单输入上按回车键使其失去焦点

[英]Press enter on form input to make it lose focus

I have a form with an input box and hidden submit field:我有一个带有输入框和隐藏提交字段的表单:

<form action="javascript:void(0);">
    <input type="text">
    <input type="submit" style="display:none;">
</form>

I would like to make it so that when you click enter, the input box simply loses focus.我想让它当你点击回车时,输入框只是失去焦点。

How can I accomplish this?我怎样才能做到这一点?

Try this out.试试这个。 Please note that you need to include jquery file for this to work.请注意,您需要包含 jquery 文件才能使其工作。

<form action="javascript:void(0);">
    <input type="text" id="txtFocus">
    <input type="submit" style="display:none;" id="btnHidden">
</form>
<script>
$("#btnHidden").on('click', function() {
        $('#txtFocus').blur();
});
</script>

Give your input an id for convenience, and you can do this with this little function using plain javascript为方便起见,为您的输入提供一个 id,您可以使用普通的 javascript 使用这个小函数来完成此操作

<form action="javascript:void(0);">
    <input id="input1" type="text">
    <input type="submit" style="display:none;">
</form>
<script>
document.getElementById('input1').addEventListener('keyup',function(e){
    if (e.which == 13) this.blur();
});
</script>

Avoid the ID lookup in the JS code by the following (tested on Firefox and Chrome).通过以下方法避免在 JS 代码中查找 ID(在 Firefox 和 Chrome 上测试)。 Submit by input loss of focus, possibly triggered by form submit.通过输入失去焦点提交,可能由表单提交触发。

 function myFunction(input) { input.value = input.value.toUpperCase(); return false; }
 <form onsubmit="this.textfield.blur();return false"> <input type="text" id="textfield" onfocusout="myFunction(this)"> <input type="submit" style="display:none;" /> </form>

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

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