javascript 触发按钮单击文本框中的 Enter 键丢失其值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15710000/
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-10-27 01:48:48  来源:igfitidea点击:

Trigger a button click on the Enter key in a text box misses its value

javascriptjquery

提问by cMinor

I have

我有

Html:

网址:

<form  action="" method="post"  id="contactForm">
    <input id='inputbox' name="inputbox" type="text" />
    <button type="button" id='search'> search </button>
</form>

JavaScript

JavaScript

$(document).ready(function() {
    $("#inputbox").keyup(function(event){
        if(event.keyCode == 13){
            $("#search").click();
        }
    });

    $('#search').click(function(){
         var inputbox= $("#inputbox").val();  
        //stuff
    });
});        

inputboxvalue is nothing when I press enter, however if I click on button It works perfectly with same input value

当我按下回车键时,输入值什么都不是,但是如果我点击按钮它可以与相同的输入值完美配合

maybe making inputboxglobal?

也许使输入 全球化?

回答by metadept

The problem is that the enter key defaults to submitting your form, even without a submit button. So you should block the submission by changing the event binding to keypressand using event.preventDefault(), like this:

问题是即使没有提交按钮,输入键默认为提交表单。因此,您应该通过将事件绑定更改为keypress并使用来阻止提交event.preventDefault(),如下所示:

$("#inputbox").keypress(function(event){
    if(event.keyCode == 13){
        event.preventDefault();
        $("#search").click();
    }
});

Alternatively, you could use .submit()to trigger your function, change the input type to submit, and avoid separate handling for keys and clicks.

或者,您可以使用.submit()触发您的功能,更改输入类型以提交,并避免单独处理键和点击。

HTML:

HTML:

<form action="" method="post" id="contactForm">
    <input id='inputbox' name="inputbox" type="text" />
    <input type="submit" value="Search">
</form>

JavaScript:

JavaScript:

$(document).ready(function() {
    $("#contactForm").submit(submitSearch);
}); 

function submitSearch(event) {
     event.preventDefault();

     //do other stuff
     alert($("#inputbox").val());
}