如何通过Enter键触发“搜索”按钮

时间:2015-08-16 05:15:03

标签: search enter

我是新来的。我想添加一些代码,除了光标点击之外,还允许我使用回车键在通过文本框提交的位置初始化谷歌地图。我有点击部分,输入键,而不是:(

<input id="address" type="text">
<input id="search" type="button" value="search" onClick="search_func()">

<script>
  function search_func() {
    var address = document.getElementById("address").value;
    initialize();
  }
</script>

3 个答案:

答案 0 :(得分:1)

以下是您的解决方案:

<!DOCTYPE html>

<html>

<head>
<title>WisdmLabs</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<style>

</style>

</head>

<body>

<input id="address" type="text" onkeypress="handle(event)" placeholder="Type something here">
<input id="search" type="button" value="search" onClick="search_func()">

<script>

function search_func(){
	address=document.getElementById("address").value;
	//write your specific code from here	
	alert("You are searching: " + address);
}

function handle(e){
	address=document.getElementById("address").value;
    if(e.keyCode === 13){
		//write your specific code from here
    	alert("You are searching: " + address);
    }
	return false;
}

</script>


</body>

</html>

随时提出任何疑问或建议。

答案 1 :(得分:0)

function search_func(e)
{
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('search').click();
        return false;
    }
    return true;
}

答案 2 :(得分:0)

你想要在你的文本框中添加一个监听器,当你输入的键被输入时(13是要输入的keyCode),在keydown上激活search_func

<input id="address" type="text" onkeydown="key_down()">
<input id="search" type="button" value="search" onClick="search_func()">

<script>
  function key_down(e) {
    if(e.keyCode === 13) {
      search_func();
    }
  }

  function search_func() {
    var address = document.getElementById("address").value;
    initialize();
  }
</script>