Javascript 在输入类型=“文本”上按“输入”,如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10905345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:31:14  来源:igfitidea点击:

Pressing 'enter' on a input type="text", how?

javascriptjqueryhtml

提问by Bastien Vandamme

I am facing a problem I can not solve JQuery Javascript. Can you help me and help me understand.First here is my code :

我面临一个问题,我无法解决 JQuery Javascript。你能帮助我并帮助我理解。首先这是我的代码:

        (...)

        <script type="text/javascript">

        // Autocomplete suggestions
        $(function () {
            $("#autoCompInput").autocomplete({
                source: "/Suggestions",
                minLength: 3,
                select: function (event, ui) {
                    if (ui.item) {
                        $("#autoCompInput").val(ui.item.value);
                        $("form").submit();
                    }
                }
            });
        });

        // Provide search results
        $(function () {
            $("#autoCompSearch").click(function () {
                var searchParameters = $("#autoCompInput").val();

                var jsonData = JSON.stringify(searchParameters, null, 2);
                window.location = "/Search?criteria=" + searchParameters;
            });
        });

    </script>

    (...)

    <input class="ui-autocomplete-input" id="autoCompInput" role="textbox" aria-haspopup="true" size="50" autocomplete="off" aria-autocomplete="list" value = "@ViewBag.SearchInfo"/>
            <a id= "autoCompSearch" href = "#" ><img src="@Url.Content("~/Content/Menu/Images/magnifier.png")" alt="Search" /></a>

    (...)

With this code I can't use the 'Enter' key to execute my search. When the user is in the input autoCompInput I would like to be able to detect if he press 'enter' and launch the submit. I read I must add a onkeyup="onKeyPressed(event)" event but I don't understand how to write the javascipt associated with the command. I tried but without success... Do you have a solution for me?

使用此代码,我无法使用“Enter”键执行搜索。当用户在输入 autoCompInput 中时,我希望能够检测他是否按“输入”并启动提交。我读到我必须添加一个 onkeyup="onKeyPressed(event)" 事件,但我不明白如何编写与该命令关联的 javascipt。我试过但没有成功......你有什么解决方案吗?

Thank you,

谢谢,

回答by workoholic

You should bind the keypress event to your input

您应该将按键事件绑定到您的输入

$("#autoCompInput").bind("keypress", {}, keypressInBox);

function keypressInBox(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 13) { //Enter keycode                        
        e.preventDefault();

        $("yourFormId").submit();
    }
};

回答by FishBasketGordo

With similar HTML:

使用类似的 HTML:

<input type="text" id="myTxt" />
<input type="submit" id="mySubmit" />

This script (which uses the latest jQuery 1.7.2) should do it:

这个脚本(使用最新的jQuery 1.7.2)应该这样做:

$('#mySubmit').click(function() {
    alert('Submitted!');
    return false;
});

$('#myTxt').on('keyup', function(e) {
    if (e.keyCode === 13) {
        $('#mySubmit').click();
    }
});

Here's a working example.

这是一个工作示例

回答by Angry 84

To assign a keyup event in jquery

在 jquery 中分配 keyup 事件

 $("#autoCompInput").keyup(function(event) {
                if (event.keyCode==13) {
                    alert('enter key');
                }
            });

回答by santiago arizti

I think there is a better and more standard solution to this type of problem.

我认为对于这类问题有一个更好、更标准的解决方案。

you can have a GET form around those inputs and whenever you press enter on any input inside that form, it will be submitted to whatever is in the action attribute of the form. This is how it would look like (I took your code but I am removing the bits irrelevant for my answer):

您可以在这些输入周围创建一个 GET 表单,并且每当您在该表单内的任何输入上按 Enter 键时,它都会被提交到表单的 action 属性中的任何内容。这就是它的样子(我拿走了你的代码,但我正在删除与我的答案无关的部分):

<form id="idForJqueryOnly" action="/Search" method="GET">
  <input type="text" name="criteria" value="someuserinput"/>
  <button type="submit"><img src="...")" alt="Search" /></button>
</form>

This is standard browser behaviour. So, what the form does? when submitted the browser creates a URL like this: http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinputWhat happened is that the browser took all the inputs with name and value (and not disabled) from the form and serialized them into url form. Now, the submit event can be triggered by pressing enter on any of the inputs inside, including buttons as long as the buttons don't have the attribute type="button".

这是标准的浏览器行为。那么,表格有什么作用呢?当提交时,浏览器创建一个像这样的 URL: http://yourserverguesedfromthecurrenturl/Search?criteria=someuserinput发生的事情是浏览器从表单中获取所有带有名称和值(并且没有禁用)的输入并将它们序列化为 url 表单。现在,提交事件可以通过在里面的任何输入上按回车键来触发,包括按钮,只要按钮没有属性 type="button"。

If you wanted to do more things with the data with javascript before going to the search page, you can do this with jquery:

如果你想在进入搜索页面之前用 javascript 对数据做更多的事情,你可以用 jquery 做到这一点:

$("#idForJqueryOnly").submit(function(){
   // here you can do stuff like serialize the form, or sanitize the input of tue user.
  var data = $("#idForJqueryOnly").serialize();
  $("[name=criteria]").val($("[name=criteria]").val().customSanitizeMethod());

  // if you return false, the form will not submit, say, for validation errors:
  return customValidator.isFormValid("#idForJqueryOnly");
})